为什么这些正则表达式不同? [英] Why are these regular expressions different?
问题描述
我正在寻找有撇号的线条,并尝试了一些看起来与我完全相同的表情。然而,有些人工作,其他人没有。为什么我得到以下行为:
egrep \'file#按预期工作
egrep \'file#似乎返回所有行
egrep[\']file#按预期工作
egrep'\''file#似乎等待更多输入
单双引号在逃避时有不同之处。把 echo
放在前面,看看实际发送到 egrep
的内容:
$ echo egrep \'文件
egrep'文件
$ echo egrep\'文件
egrep \'文件
$ echo egrep[\']file
egrep [\'] file
$ echo egrep'\''file
>
最后一种情况是提示输入更多信息,因为您仍在单引号表达式中:而不是单引号中的转义引用( \'
)(因为这不是您如何转义单引号的方式)。它是单引号之间的反斜杠, 。
顺便说一句,为了避免单引号字符串中的单引号,请使用如下构造:
$ echo'foo'\''bar'
foo'bar
实际做的是在两个单引号字符串之间放置一个裸字面引号( \'
)。这些都是隐式连接在一起的。
我不知道为什么\'
匹配所有行但它的确如此。)
I am looking for lines that have an apostrophe in them and tried a few expressions that seemed identical to me; however, some worked and others didn't. Why did I get the following behavior:
egrep \' file # works as expected
egrep "\'" file # seems to return all lines
egrep "[\']" file # works as expected
egrep '\'' file # seems to be waiting for more input
Single vs. double quotes have differences when it comes to escaping. Put echo
in front to see what actually gets sent to egrep
:
$ echo egrep \' file
egrep ' file
$ echo egrep "\'" file
egrep \' file
$ echo egrep "[\']" file
egrep [\'] file
$ echo egrep '\'' file
>
The last case is prompting for more input because you're still within a single-quoted expression: it's not an escaped quote (\'
) in single quotes (since that isn't how you escape single quotes.) It's a backslash between single quotes, with a trailing opening quote.
Incidentally, to escape a single quote in a single-quoted string, use a construction like this:
$ echo 'foo'\''bar'
foo'bar
What this is actually doing is putting a naked literal quote(\'
) between two single-quoted strings. These are then all implicitly concatenated together.
I have no idea why "\'"
matches all lines (but it indeed seems to.)
这篇关于为什么这些正则表达式不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!