Regex – Can you make just part of a regex case-insensitive


I've seen lots of examples of making an entire regular expression case-insensitive. What I'm wondering about is having just part of the expression be case-insensitive.

For example, let's say I have a string like this:


What if I want to match all occurrences of "foo" regardless of case but I only want to match the upper-case "BAR"s?

The ideal solution would be something that works across regex flavors but I'm interested in hearing language-specific ones as well (Thanks Espo)


The link Espo provided was very helpful. There's a good example in there about turning modifiers on and off within the expression.

For my contrived example, I can do something like this:


which makes the match case-insensitive for just the foo portion of the match.

That seemed to work in most regex implementations except Javascript, Python, and a few others (as Espo mentioned).

The big ones that I was wondering about (Perl, PHP, .NET) all support inline mode changes.

Best Solution

Perl lets you make part of your regular expression case-insensitive by using the (?i:) pattern modifier.

Modern regex flavors allow you to apply modifiers to only part of the regular expression. If you insert the modifier (?ism) in the middle of the regex, the modifier only applies to the part of the regex to the right of the modifier. You can turn off modes by preceding them with a minus sign. All modes after the minus sign will be turned off. E.g. (?i-sm) turns on case insensitivity, and turns off both single-line mode and multi-line mode.

Not all regex flavors support this. JavaScript and Python apply all mode modifiers to the entire regular expression. They don't support the (?-ismx) syntax, since turning off an option is pointless when mode modifiers apply to the whole regular expressions. All options are off by default.

You can quickly test how the regex flavor you're using handles mode modifiers. The regex (?i)te(?-i)st should match test and TEst, but not teST or TEST.


Related Question