本文介绍了grep:匹配字面上的“+”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在我的sql脚本中找到(+),即Oracle外部联接表达式。意识到+,(和)都是特殊的正则表达式字符,我尝试:

 
grep\ \ + \)*

现在,这会返回(+),但是其他行也一样。 (看起来在同一行上有打开和关闭括号的任何东西。)回想一下,括号只是特殊的扩展grep,我尝试:

 
grep (\ +)*
grep(\\ +)*

包含()的行。假设+不能被转义,我尝试了一个老技巧:

 
grep([+])*

这样工作。

问题:有人可以解释+是怎么回事,字符?是否有更少的kludgy方式匹配(+)?



(我使用cygwin grep命令。)



编辑:感谢您的解决方案。 - 现在我看到,根据Bruno引用的GNU grep手册 \ + 基本 +其扩展含义,因此匹配一个或多个(s后跟一个)。在我的文件中总是()。

解决方案

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

由于您希望字符<$ c>的普通 $ c>( + 目的:

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


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 "()".

解决方案

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:

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

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

这篇关于grep:匹配字面上的“+”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 23:15