正则表达式 - `^`、`$` 和 `\A`、`\Z` 之间的差异 [英] REGEX - Differences between `^`, `$` and `\A`, `\Z`

查看:188
本文介绍了正则表达式 - `^`、`$` 和 `\A`、`\Z` 之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,re 提出了以下边界匹配.

  • ^ 匹配行首.
  • $ 匹配行尾.
  • \A 匹配输入的开头.
  • \Z 匹配输入的结尾.

你能给我一个具体的例子来说明 ^$\A\Z<之间的真正区别吗?/代码> ?

解决方案

只有当您使用 re.Mre.MULTILINE 多行标志:

<预><代码>>>>re.search(r'^word', '第一行\n第二行的单词\n', flags=re.M)<_sre.SRE_Match 对象在 0x10124f578>>>>re.search(r'\Aword', '第一行\n第二行的单词\n', flags=re.M) 是 None真的

其中 ^的开头匹配(在换行符之后).$ 匹配行尾:

<预><代码>>>>re.search(r'word$', '第一行单词\n第二行\n', flags=re.M)<_sre.SRE_Match 对象在 0x10123e1d0>>>>re.search(r'word\Z', '第一行单词\n第二行\n', flags=re.M) 为无真的

来自文档:

<块引用>

re.M
re.MULTILINE

指定时,模式字符 '^' 匹配字符串的开头和每行的开头(紧跟在每个换行符之后);并且模式字符 '$' 在字符串的末尾和每行的末尾(紧接在每个换行符之前)匹配.默认情况下,'^' 只匹配字符串的开头,'$' 只匹配字符串的结尾和换行符(如果有)之前的位置字符串的结尾.

\A 总是 匹配在字符串的开头,\Z 总是在末尾.

As I know, re proposes the following boundary matches.

  • ^ matches at the beginning of a line.
  • $ matches at the end of a line.
  • \A matches the beginning of the input.
  • \Z matches the end of the input.

Can you give me a concret example showing a real difference between between ^, $ and \A, \Z ?

解决方案

The difference only becomes apparent when you use the 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

where ^ matched at the start of a line (following a newline). $ matches at the end of a line:

>>> 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

From the documentation:

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 always matches at the start of the string regardless, \Z always at the end.

这篇关于正则表达式 - `^`、`$` 和 `\A`、`\Z` 之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆