据我所知,re
提出了以下边界匹配。
^
匹配行首。$
匹配行尾。\A
匹配输入的开头。\Z
匹配输入的结尾。
你能给我一个具体的例子来说明 ^
、$
和 \A
、\Z< 之间的真正区别吗
?
最佳答案
只有在使用 re.M
or re.MULTILINE
multiline flag 时差异才会变得明显:
>>> re.search(r'^word', 'Line one\nword on line two\n', flags=re.M)
<_sre.SRE_Match object at 0x10124f578>
>>> re.search(r'\Aword', 'Line one\nword on line two\n', flags=re.M) is None
True
其中 ^
在 行 的开头匹配(在换行符之后)。 $
匹配行尾:
>>> re.search(r'word$', 'Line one word\nLine two\n', flags=re.M)
<_sre.SRE_Match object at 0x10123e1d0>
>>> re.search(r'word\Z', 'Line one word\nLine two\n', flags=re.M) is None
True
来自文档:
re.M
re.MULTILINE
When specified, the pattern character
'^'
matches at the beginning of the string and at the beginning of each line (immediately following each newline); and the pattern character'$'
matches at the end of the string and at the end of each line (immediately preceding each newline). By default,'^'
matches only at the beginning of the string, and'$'
only at the end of the string and immediately before the newline (if any) at the end of the string.
\A
总是 在字符串的开头匹配,而 \Z
总是在结尾。
关于python - 正则表达式 - `^`、 `$` 和 `\A`、 `\Z` 之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22519318/