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
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
(?m) where you would use
/m in Perl, or
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.
2 thoughts on “Bringing regex modifiers into the regex”
I use this all the time, for me (?i) beats finding the mouse and the ‘case (in)sensitive’ toggle.
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.