我如何使用正则表达式来匹配“结尾”而不允许在那里换行?

How can I use regex to match “the end” without allowing a newline there?

^abc$ 匹配字符串 abc,但也匹配 abc\n(带有尾随换行符)。

如何让它只匹配没有换行符的字符串?

(考虑到 Python,但应该是一般的正则表达式问题。)

而不是 $ 使用 \Z 只匹配字符串的末尾。

>>> re.match(r'^abc\Z', 'abc')
<_sre.SRE_Match object at 0x02469560>
>>> re.match(r'^abc\Z', 'abc\n')
>>>

注:这个答案具体取决于Python中\Z的含义。此概念是 often spelled \z in other regex implementations. You could also use a negative-lookahead assertion, but the syntax for that also varies across regex implementations. See ,用于在 Python.

中使用负先行断言的示例

我不知道这是否适用于 python 中的正则表达式引擎,但您可以查看。negative\positive look ahead。 您可以使用否定前瞻来查看 \n 是否在 "abc".

之后

使用否定前瞻来确保没有 \n:

>>> re.search(r'^abc(?!\n)$', s1)
>>> re.search(r'^abc(?!\n)$', s2)
<_sre.SRE_Match object at 0x10a716a58>
>>> re.search(r'^abc(?!\n)$', 'abcdefg')
>>> 

这在大多数其他现代正则表达式变体中都一样。

Perl:

  DB<11> print 'match' if "abc\n" =~ /^abc(?!\n)$/

  DB<12> print 'match' if "abc" =~ /^abc(?!\n)$/              
match

Ruby:

irb(main):031:0> "abc"[/^abc(?!\n)$/]
=> "abc"
irb(main):032:0> "abc\n"[/^abc(?!\n)$/]
=> nil

PHP:

$ php -r 'print preg_match("/^abc(?!\n)$/", "abc\n");'
0
$ php -r 'print preg_match("/^abc(?!\n)$/", "abc");'
1

这是一个否定的前瞻,所以如果它在行尾,但在其他任何地方都不会找到匹配项。

>>> re.search('abc(?!\n)','abc\n')
>>> re.search('abc(?!\n)','abc')
<_sre.SRE_Match object at 0x103eceac0>