Lin Ma Lin Ma - 3 months ago 14
Python Question

python 2.7 regular expression match with \r\n in string

Wondering if any ways to match string contains

\r \n
? It seems the same regular expression match does not work if input string content contains
\r \n
. Using Python 2.7.

works pretty good,

import re

content = '{(1) hello (1)}'
reg = '{\(1\)(.*?)\(1\)}'
results = re.findall(reg, content)

print results[0]

prog = re.compile(reg)
results = prog.findall(content)

print results[0]


will not work when add
\r \n


import re

content = '{(1) hello \r\n (1)}'
reg = '{\(1\)(.*?)\(1\)}'
results = re.findall(reg, content)

print results[0]

prog = re.compile(reg)
results = prog.findall(content)

print results[0]


regards,
Lin

Answer

This works:

>>> import re
>>> 
>>> content = '{(1) hello \r\n (1)}'
>>> reg = '{\(1\)(.*?)\(1\)}'
>>> results = re.findall(reg, content, re.DOTALL)
>>> 
>>> print results[0]
 hello 

>>> 
>>> prog = re.compile(reg, re.DOTALL)
>>> results = prog.findall(content)
>>> 
>>> print results[0]
 hello 

>>> 

From Python Docs:

'.' (Dot.) In the default mode, this matches any character except a newline. If the DOTALL flag has been specified, this matches any character including a newline.

Comments