Lessons · Regex · (?i): a flag inside the pattern
A flag written inside the pattern
(?i) at the front turns on case-insensitive matching for the whole pattern; (?i:...) turns it on for just that group.
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
A pattern kept in a config file or a database column has nowhere to pass a flag. Written inside, it carries its own settings.
How to think about it
Whole pattern, or one part? The bare form must be at the very start; the scoped form goes where it applies and means what it looks like.
Worked example
re.search(r'(?i)hello', 'HELLO').group()The whole pattern, relaxed about case.
re.search(r'(?i:ab)c', 'ABc').group()Only the ab is relaxed; the c is not.
re.search(r'(?i:ab)c', 'ABC')Which is why this finds nothing.
Your turn
Relax the case of the ab only, not the c.
(?:ab)c
Test a pattern against real text
The trap
A bare (?i) anywhere but the start raises 'global flags not at the start of the expression'. Partway through, the scoped form is the only one.
Practise (?i): a flag inside the pattern on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.