Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

python - REGEX - Differences between `^`, `$` and `A`, ``

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.
  • matches the end of the input.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The difference only becomes apparent when you use the re.M or re.MULTILINE multiline flag:

>>> re.search(r'^word', 'Line one
word on line two
', flags=re.M)
<_sre.SRE_Match object at 0x10124f578>
>>> re.search(r'Aword', 'Line one
word on line two
', 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
Line two
', flags=re.M)
<_sre.SRE_Match object at 0x10123e1d0>
>>> re.search(r'word', 'Line one word
Line two
', 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, always at the end.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...