Lessons · Regex · flags: i, m, s and x
Switches on the whole pattern
i ignores case, m makes ^ and $ match on every line, s lets the dot take newlines, x gives the pattern room to breathe. A flag applies to the WHOLE pattern.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Case-insensitive search, reading a whole file as one string, and making a long pattern something a colleague can read.
How to think about it
Ask what the pattern needs to stop being strict about: case, line ends, the newline itself, or its own layout. Turn on exactly those and nothing else.
Worked example
pattern: (?i)errorThe flag written inside the pattern, at the front.
text: Error: disk. error: netBoth match, whatever the case.
in Python: re.findall(r'error', text, re.I)The same switch, handed to the call instead.
Your turn
Match 'error' whatever its case, with the flag written inside the pattern.
(?)error
Test a pattern against real text
The trap
There is no 'find them all' flag in Python: findall already returns every match and re.sub already replaces every one unless you pass count. Reaching for a g is the commonest habit a JavaScript regex brings across.