grep:匹配文字“+”

发布于 2024-07-07 05:17:41 字数 636 浏览 5 评论 0原文

我需要在我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

原谅过去的我 2024-07-14 05:17:42

GNU grep(包含在 Cygwin 中)支持两种正则表达式语法:基本语法和扩展语法。 grep 使用基本正则表达式,egrepgrep -E 使用扩展正则表达式。 grep 手册 中的基本区别如下:

在基本正则表达式中,元字符 ?+{|(< /code> 和 ) 失去其特殊含义; 而是使用反斜杠版本 \?\+\{\|\(\)


由于您想要字符 ( + )普通含义,因此以下两种形式之一都应该适用你的目的:

grep "(+)" *       # Basic
egrep "\(\+\)" *   # Extended

GNU grep (which is included in Cygwin) supports two syntaxes for regular expressions: basic and extended. grep uses basic regular expressions and egrep or grep -E uses extended regular expressions. The basic difference, from the grep manual, is the following:

In basic regular expressions the metacharacters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \).

Since you want the ordinary meaning of the characters ( + ), either of the following two forms should work for your purpose:

grep "(+)" *       # Basic
egrep "\(\+\)" *   # Extended
汐鸠 2024-07-14 05:17:42

您可能需要添加一些反斜杠,因为 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文