grep:匹配文字“+”
我需要在我的 sql 脚本(即 Oracle 外连接表达式)中查找“(+)”的出现。 意识到“+”、“(”和“)”都是特殊的正则表达式字符,我尝试:
grep "\(\+\)" *
现在这确实返回“(+)”的出现,但也返回其他行。 (似乎任何带有左括号和右括号的东西都在同一行上。)回想起括号仅对扩展 grep 是特殊的,我尝试过:
grep "(\+)" * grep "(\\+)" *
这两个都只返回包含“()”的行。 因此,假设“+”无法转义,我尝试了一个老技巧:
grep "([+])" *
这有效。 我使用非正则表达式工具交叉检查了结果。
问题:有人能解释一下“+”字符究竟是怎么回事吗? 有没有一种不太笨拙的方法来匹配“(+)”?
(我正在使用 cygwin grep 命令。)
编辑:感谢您的解决方案。 -- 现在我发现,根据 Bruno 引用的 GNU grep 手册,“\+
”在基本表达式中使用时给出了“+”的扩展 的意思,因此匹配一个或多个“(”后跟一个“)”。 在我的文件中,总是“()”。
I need to find occurrences of "(+)" in my sql scripts, (i.e., Oracle outer join expressions). Realizing that "+", "(", and ")" are all special regex characters, I tried:
grep "\(\+\)" *
Now this does return occurrences of "(+)", but other lines as well. (Seemingly anything with open and close parens on the same line.) Recalling that parens are only special for extended grep, I tried:
grep "(\+)" * grep "(\\+)" *
Both of these returned only lines that contain "()". So assuming that "+" can't be escaped, I tried an old trick:
grep "([+])" *
That works. I cross-checked the result with a non-regex tool.
Question: Can someone explain what exactly is going on with the "+" character? Is there a less kludgy way to match on "(+)"?
(I am using the cygwin grep command.)
EDIT: Thanks for the solutions. -- And now I see that, per the GNU grep manual that Bruno referenced, "\+
" when used in a basic expression gives "+" its extended meaning, and therefore matches one-or-more "("s followed by a ")". And in my files that's always "()".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
GNU grep(包含在 Cygwin 中)支持两种正则表达式语法:基本语法和扩展语法。
grep
使用基本正则表达式,egrep
或grep -E
使用扩展正则表达式。 grep 手册 中的基本区别如下:由于您想要字符
(
+
)
的普通含义,因此以下两种形式之一都应该适用你的目的:GNU grep (which is included in Cygwin) supports two syntaxes for regular expressions: basic and extended.
grep
uses basic regular expressions andegrep
orgrep -E
uses extended regular expressions. The basic difference, from the grep manual, is the following:Since you want the ordinary meaning of the characters
(
+
)
, either of the following two forms should work for your purpose:您可能需要添加一些反斜杠,因为 shell 正在吞噬它们。
ETA:实际上,我刚刚在 Cygwin 上尝试过,
grep "(+)"
似乎可以很好地满足您的需求。You probably need to add some backslashes because the shell is swallowing them.
ETA: Actually, I just tried on my Cygwin and
grep "(+)"
seems to work just fine for what you want.