Flags

suggest change

For some special cases we need to change the behavior of the Regular Expression, this is done using flags. Flags can be set in two ways, through the flags keyword or directly in the expression.

Flags keyword

Below is an example for re.search, but it works for most functions in the re module.

m = re.search("b", "ABC")  
m is None
# Out: True

m = re.search("b", "ABC", flags=re.IGNORECASE)
m.group()
# Out: 'B'

m = re.search("a.b", "A\nBC", flags=re.IGNORECASE) 
m is None
# Out: True

m = re.search("a.b", "A\nBC", flags=re.IGNORECASE|re.DOTALL) 
m.group()
# Out: 'A\nB'

Common Flags

Flag Short description
re.IGNORECASE, re.I Makes the pattern ignore the case
re.DOTALL, re.S Makes . match everything including newlines
re.MULTILINE, re.M Makes ^ match the beginning of a line and $ the end of a line
re.DEBUG Turns on debug information

For the complete list of all available flags check the docs.

Inline flags

Flags can be written inside the expression as (?aiLmsux), using one or more of a, i, L, m, s, u, and x. The group matches the empty string and sets the corresponding flags for the whole expression: re.A (ASCII-only), re.I (ignore case), re.L (locale dependent), re.M (multi-line), re.S (dot matches all), re.U (Unicode; redundant for str patterns), and re.X (verbose). See the docs.

Since Python 3.11 these flags are allowed only at the start of the expression. Anywhere else, re.compile raises re.error (global flags not at the start of the expression). To change flags for only part of a pattern, use a scoped group such as (?i:...).

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents