给定以下字符串
45op0
tr ico
JJB Be
tyuh
113-4997
202076
acure
sala mandra我正在寻找以下结果:
45op0;113-4997
tr ico;202076
JJB Be;acure
tyuh;sala mandra基本上将底部的4行和顶部的4行按照它们的原始顺序组合在一个;分隔的列表中。
这是我到目前为止拥有的正则表达式:
^((?:[^\r*\n]*[\r*\n]){4})([\s\S]*)替换为:
$1;$2如此demo中所示
正如您所看到的,这不会给出扩展的结果。
任何帮助都将不胜感激。
发布于 2020-05-03 11:24:47
您可以使用正则表达式
^(.+)\r?\n(?=(?:.*\r?\n){3}(.+))对于给定的示例,有四个匹配:45op0、tr ico、JJB Be和tyuh。每个匹配都有两个捕获组。第一个捕获组包含匹配本身。对于第一个匹配(45op0),捕获组2包含包含113-4997,它是在正前视中捕获的。然后,可以将两个捕获组的内容连接起来,用分号分隔,以返回45op0;113-4997
同样,对于第二个匹配,捕获组2包含202076,依此类推。
当到达行113-4997时,它被保存在cap grp1中,接下来的三行被消耗,然后正则表达式失败,因为后面没有非空行。对于接下来的几行,正则表达式失败,因为它无法跳过三行。
PCRE正则表达式引擎执行以下操作。
^(.+) match a line with 1+ chars, excl. line terminators,
in cap grp 1
\r?\n match the newline and possible carriage return
(?= begin a positive lookahead
(?:.*\r?\n) match an entire line in a non-cap group
{3} execute the non-cap group 3 times (skip 3 lines)
(.+) match a line with 1+ chars, excl. line terminators,
in cap grp 2
) end positive lookaheadhttps://stackoverflow.com/questions/61569049
复制相似问题