简体   繁体   English

在 Grep 中为 Windows 命令行使用正则表达式

[英]Using regex in Grep for Windows command line

I want to capture all lines which contain exactly 3 fields, where a field is any string (possibly empty) followed by a |我想捕获恰好包含 3 个字段的所有行,其中字段是任何字符串(可能为空),后跟| (and there may be some final text at the end of the line). (并且可能在行尾有一些最终文本)。

I managed to build a regex which seems to do exactly what I want我设法构建了一个似乎完全符合我要求的regex

^(?:[^\|]*\|){3}[^\|]*$

and when I try it on 101regex it seems to work just fine.当我在101regex上尝试它时,它似乎工作得很好。

However, I am having problems to run this regex on the Windows command line via grep and I guess it has something to do with the proper escaping.但是,我无法通过grep在 Windows 命令行上运行此regex ,我想这与正确的 escaping 有关。

I tried我试过了

grep -E '^^(?:[^^^\^|]*^\^|){3}[^^^\^|]*$' test.txt
grep -E '^^(?:[^^^|]*^|){3}[^^^|]*$' test.txt

but nothing helped.但没有任何帮助。 Any ideas?有任何想法吗?


Test Input测试输入

0|1|2|3
0|1|2|
|1|2|3
|1|2|
|1|2
|1|
0|1|2
0|1|
|1|2|3|4
|1|2|3|
0|1|2|3|4
0|1|2|3|

In grep , when you use POSIX ERE regex engine, you need to avoid backslashes in bracket expressions and non-capturing groups:grep中,当您使用 POSIX ERE 正则表达式引擎时,您需要避免括号表达式和非捕获组中的反斜杠:

grep -E "^([^|]*\|){3}[^|]*$" test.txt

Here, [^\|] is turned into [^|] (since POSIX bracket expressions do not treat escaped chars as regex escapes) and (?: is replaced with ( , ie the group was made capturing since non-capturing ones are not supported.在这里, [^\|]变成[^|] (因为 POSIX 括号表达式不将转义字符视为正则表达式转义)并且(?:替换为( ,即该组被捕获,因为非捕获的不是支持的。

See proof it is working:查看它正在工作的证据:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM