python - 正则表达式 - `^`、 `$` 和 `\A`、 `\Z` 之间的差异

标签 python regex

据我所知,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/

相关文章:

python - 使用谷歌云函数生成Python脚本

python - MVC tkinter 模型。在框架之间切换,添加新框架

Python - 如何在每 3 个字符上添加空格?

python - 我可以更新文本文件的一部分吗?我已经建立了一个登录系统,我想计算一个用户登录了多少次

python - Pandas .str.replace 和不区分大小写

时间:2019-03-08 标签:c#正则表达式: find placeholders as substring

python - 从列表中删除重复项

python - 网页抓取 - 进入第 2 页

ruby - 如何进行忽略控制字符的文本搜索?

用于验证组织/公司编号的 c# 代码?