C# inline regular expression syntax and usage
I found this brilliant answer at Stack overflow. It is way more clearer and useful than Microsoft's official one
You can use inline modifiers as follows:
// case insensitive match
Regex MyRegex = new Regex(@"(?i)[a-z]+"); // case insensitive match
or, inverse the meaning of the modifier by adding a minus-sign:
// case sensitive match
Regex MyRegex = new Regex(@"(?-i)[a-z]+"); // case sensitive match
or, switch them on and off:
// case sensitive, then case-insensitive match
Regex MyRegex = new Regex(@"(?-i)[a-z]+(?i)[k-n]+");
Alternatively, you can use the mode-modifier span syntax using a colon :
and a grouping parenthesis, which scopes the modifier to only that group:
// case sensitive, then case-insensitive match
Regex MyRegex = new Regex(@"(?-i:[a-z]+)(?i:[k-n]+)");
You can use multiple modifiers in one go like this (?is-m:text)
, or after another, if you find that clearer (?i)(?s)(?-m)text
(I don't). When you use the on/off switching syntax, be aware that the modifier works till the next switch, or the end of the regex. Conversely, using the mode-modified spans, after the span the default behavior will apply.
Finally: the allowed modifiers in .NET are (use a minus to invert the mode):
x
allow whitespace and comments
s
single-line mode
m
multi-line mode
i
case insensitivity
n
only allow explicit capture (.NET specific)