Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'\n' 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?

like image 848
wei Avatar asked Feb 04 '13 15:02

wei


People also ask

How do you match a new line in Python?

To match the new line regex in Python, use the pattern \n. On Linux OS, it is \n; on Windows, the line break matches with \r\n, and in the old version of Mac, it is \r.

How do you match with newline?

"\n" matches a newline character.

How do you match part of a string in Python?

Use the string method startswith() for forward matching, i.e., whether a string starts with the specified string. You can also specify a tuple of strings. True is returned if the string starts with one of the elements of the tuple, and False is returned if the string does not start with any of them.

How do you match a character in Python?

Using m option allows it to match newline as well. Matches any single character in brackets. Matches 0 or more occurrences of preceding expression. Matches 1 or more occurrence of preceding expression.


1 Answers

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

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

Notice that re translates the \n (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\ndog',s).group(0) 'cat\ndog' >>> re.match(r'^cat$\ndog',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$\ndog',s,re.M).group(0) #matches. 'cat\ndog' 
like image 111
mgilson Avatar answered Sep 28 '22 05:09

mgilson