给定以下字符串
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条线按原来的顺序组合在一起。;
分隔的列表。
这是我目前掌握的regex。
^((?:[^\r*\n]*[\r*\n]){4})([\s\S]*)
subituted by:
$1;$2
如图所示 演示
正如你所看到的,这并没有给出表达的结果。
任何帮助将是非常感激的。
你可以使用正则表达式
^(.+)\r?\n(?=(?:.*\r?\n){3}(.+))
对于所举的例子,有四种匹配。45op0
, tr ico
, JJB Be
和 tyuh
. 每个匹配有两个捕获组。第一个捕获组包含匹配本身。对于第一个匹配点 (45op0
),捕获组2包含包含 113-4997
,这是在正向看板中捕获的。然后将两个捕获组的内容连接起来,用分号隔开,就可以返回 45op0;113-4997
同样,对于第二个比赛采集组2包含了 202076
,以此类推。
当线 113-4997
达到后,保存在cap grp 1中,接下来的三行被消耗掉,然后由于后面没有非空行,所以regex失败。对于接下来的行,由于无法跳过三行,所以regex失败。
PCRE regex引擎执行以下操作。
^(.+) 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 lookahead