Thursday, August 11, 2011

Regular Expression match for double quotes in Python

To match a single line containing double quotes:
>>> x = '"Hello World"'
>>> re.match('"Hello World"',x).group(0)
... '"Hello World"'
To match multi lines containing double quotes:
>>> x
... '"Hello\nWorld"'
>>> re.match("""("Hello.*World")""",x,re.M|re.DOTALL)
... <_sre.SRE_Match object at 0x00D84E60>
The trick is using parenthesis "(" and ")" for grouping, otherwise following code will be reported as syntax error:
>>> x
... '"Hello\nWorld"'
>>> re.match(""""Hello.*World"""",x,re.M|re.DOTALL)

No comments:

Post a Comment