我正在尝试删除所有符合特定条件的换行符。我将Visual Studio代码与以下regex模式一起使用。
(?!;)\n但是,它仍然选择在换行前包含分号字符的换行符。
我如何才能做到这一点呢?
发布于 2018-06-20 06:20:45
(?!;)是一个消极的前瞻,它“限制”下面的\n模式与;不匹配--而且它总是正确的,因为LF符号不是;。因此,(?!;)\n等于\n,并且它匹配任何LF字符。
您可以使用
(^|[^;])\n并替换为$1,以恢复在结果文本中使用(^|[^;])模式(行首(^)或(|)除; ([^;])以外的任何字符)捕获的字符。
发布于 2018-06-20 07:26:56
这就是你所需要的
查找\n(?<!;\n)
替换为nothing。
示例
asdf
;
asdf
adsfasdf;
;
;基准测试
Regex1: (^|[^;])\n
Options: < none >, Newline only
Completed iterations: 50 / 50 ( x 1000 )
Matches found per iteration: 2
Elapsed Time: 0.43 s, 430.78 ms, 430778 µs
Matches per sec: 232,138
Regex2: \n(?<!;\n)
Options: < none >, Newline only
Completed iterations: 50 / 50 ( x 1000 )
Matches found per iteration: 2
Elapsed Time: 0.15 s, 153.75 ms, 153745 µs
Matches per sec: 650,427注意-我不会使用原始\n,因为
这种情况很少见。如果更改为\r?\n,它将同时涵盖这两种情况
案例。如果使用的是.net引擎,变量look behind就可以了。
如果没有,你可以使用\n(?<!;\n)(?<!;\r\n),它仍然会更好。
Regex3: \n(?<!;\n)(?<!;\r\n)
Options: < none >
Completed iterations: 50 / 50 ( x 1000 )
Matches found per iteration: 2
Elapsed Time: 0.18 s, 184.67 ms, 184672 µs
Matches per sec: 541,500https://stackoverflow.com/questions/50937633
复制相似问题