tags:

views:

122

answers:

1

In particular, I'd like to know if I can specify an embedded option in the pattern string that will enable multiline mode. That is, typically with Python regular expressions multiline mode is enabled like this:

pattern = re.compile(r'foo', re.MULTILINE)

I'd like a way to get multiline matching by specifying it in the pattern string, rather than using the re.MULTILINE option. You can do this in Java with the embedded (?m) expression. e.g.,

pattern = re.compile(r'(?m)foo')

Is this possible in Python, or am I required to use the re.M option? And in general, is there a good reference for embedded pattern options in Python?

+6  A: 

yes.

From the docs:

(?iLmsux) (One or more letters from the set 'i', 'L', 'm', 's', 'u', 'x'.)

The group matches the empty string; the letters set the corresponding flags: re.I (ignore case), re.L (locale dependent), re.M (multi-line), re.S (dot matches all), re.U (Unicode dependent), and re.X (verbose), for the entire regular expression. (The flags are described in Module Contents.)

This is useful if you wish to include the flags as part of the regular expression, instead of passing a flag argument to the compile() function.

Note that the (?x) flag changes how the expression is parsed. It should be used first in the expression string, or after one or more whitespace characters. If there are non-whitespace characters before the flag, the results are undefined.

nosklo