Bringing regex modifiers into the regex

Suppose you’re using a program that takes a regular expression as an argument. You didn’t get the match you expected, then you realize you’d like your search to be case-insensitive.

If you were using grep you’d go back and add a -i flag.

If you were writing a Perl script, you could add a /i at the end of the regex.

If you were using Python, you could add re.IGNORECASE as a function argument.

But the premise of the post isn’t that you’re using grep or Perl or Python. The premise is that you are using a program that takes a regular expression as an argument, and regular expression modifiers are not regular expressions per se.

However, you can incorporate regular expression modifiers into a regular expression, if your regular expression implementation supports it. In particular, you can add (?i) to a regex to indicate that the remainder of the search pattern is to be interpreted as case-insensitive. You can also use (?-i) to turn case sensitivity back on.

For example, the regex


will make the baz portion of the expression case insensitive but the rest is case sensitive. For example, the expression will match fooBaZqux but not foobazQux.

You can also use things like (?s) and (?m) where you would use /s and /m in Perl, or re.S and re.M in Python.

These scoped pattern modifiers are not supported everywhere. They were introduced in Perl and have been adopted in other languages and applications.

Related posts

2 thoughts on “Bringing regex modifiers into the regex

  1. I use this all the time, for me (?i) beats finding the mouse and the ‘case (in)sensitive’ toggle.

    Tools built on JavaScript (like VS code) unfortunately often use JS regex format, which does not support (?i) etc…

  2. Reminds me of two things:

    Friedl’s still excellent book on mastering regular expressions. And the delightful saying from programmers “you had a programming problem you solved with regular expressions; now you have two problems“ thanks for this post.

Comments are closed.