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 Pyhon. 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
foo(?i)baz(?-i)quz
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- Grep written in Perl
- Problem solving by successive approximation
- Word problems and regular expressions