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
510 views
in Technique[技术] by (71.8m points)

regex - How to match a new line character in Python raw string

I got a little confused about Python raw string. I know that if we use raw string, then it will treat '' as a normal backslash (ex. r' ' would be and n). However, I was wondering what if I want to match a new line character in raw string. I tried r'\n', but it didn't work.

Anybody has some good idea about this?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

In a regular expression, you need to specify that you're in multiline mode:

>>> import re
>>> s = """cat
... dog"""
>>> 
>>> re.match(r'cat
dog',s,re.M)
<_sre.SRE_Match object at 0xcb7c8>

Notice that re translates the (raw string) into newline. As you indicated in your comments, you don't actually need re.M for it to match, but it does help with matching $ and ^ more intuitively:

>> re.match(r'^cat
dog',s).group(0)
'cat
dog'
>>> re.match(r'^cat$
dog',s).group(0)  #doesn't match
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
>>> re.match(r'^cat$
dog',s,re.M).group(0) #matches.
'cat
dog'

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

...