grep“?”与有效匹配不符 [英] grep "?" does not match valid matches
问题描述
我想匹配文件中的标签(带有可选的括号)...容易的人会认为...正则表达式类似于 ^ \ [?MyTag \]?
。但是... Grep不喜欢它。
有趣的部分是:如果我替换?
用 *
(所以零到无限匹配,而不是零或一)它匹配所有它应该的东西,但真的这意味着功能被破坏,我不
任何输入?
在Windows上使用grep(GNU grep)2.22。
$ b $ PS:so grep就是这样...
pre $ grep -e^ \?MyTag\]? file.txt
和我的测试文件是这样的
[MyTag] hello
NotMyTag ugly
[NotMyTag] dumb
MyTag world
显然应该会显示第一行和第四行,但不会显示任何内容。
?
不是grep支持的基本正则表达式的一部分。 GNU grep支持它们作为扩展名,但你必须逃避它们: $ grep'^ \ [\?MyTag \] \?'file.txt
[MyTag] hello
MyTag world
或者,正如指出的那样,使用 grep -E
来启用扩展正则表达式。
对于GNU grep , grep
和 grep -E
之间的唯一区别,即使用基本和扩展正则表达式,就是你所拥有的
- 基本正则表达式
- 捕获组和量化必须被转义:
\(\)
和\ {\}
- 一个或多个(
+
)和替换(|
)不是BRE的一部分,但由GNU grep作为扩展支持(但需要转义:\?\ + \ | b
$ b- 扩展正则表达式
()
和{} $ c <$>
- 捕获组和量化不必转义$ c $
+
- 扩展正则表达式
支持并且不需要转义 | - 捕获组和量化必须被转义:
I want to match tags in files (with optional brackets) ... easy one would think ... the regex is something like ^\[?MyTag\]?
. But ... Grep doesn't like it. None of the lines that would be valid matches are actually matched.
The interesting part is: if I replace the ?
with a *
(so zero to infinite matches, not zero or one) it matches everything like it should, but really that would mean the feature is broken and I don't believe that.
Any input?
Using grep (GNU grep) 2.22 on Windows.
PS: so grep is like this ...
grep -e "^\[?MyTag\]?" file.txt
and my test file is like this
[MyTag] hello
NotMyTag ugly
[NotMyTag] dumb
MyTag world
which obviously should result in 1st and 4th line showing but shows nothing.
?
is not part of the basic regular expressions, which grep supports. GNU grep supports them as an extension, but you have to escape them:
$ grep '^\[\?MyTag\]\?' file.txt
[MyTag] hello
MyTag world
Or, as pointed out, use grep -E
to enable extended regular expressions.
For GNU grep, the only difference between grep
and grep -E
, i.e., using basic and extended regular expressions, is what you have to escape and what not.
- Basic regular expressions
- Capture groups and quantifying have to be escaped:
\( \)
and\{ \}
- Zero or one (
?
), one or more (+
) and alternation (|
) are not part of BRE, but supported by GNU grep as an extension (but need to be escaped:\? \+ \|
)
- Capture groups and quantifying have to be escaped:
- Extended regular expressions
- Capture groups and quantifying don't have to be escaped:
( )
and{ }
?
,+
and|
are supported and don't need be be escaped
- Capture groups and quantifying don't have to be escaped:
这篇关于grep“?”与有效匹配不符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!