Reputation: 33087
I'm using System.Text.RegularExpressions.Regex.IsMatch(testString, regexPattern) to do some searches in strings.
Is there a way to specify in the regexPattern string that the pattern should ignore case? (I.e. without using Regex.IsMatch(testString, regexPattern, RegexOptions.IgnoreCase))
Upvotes: 88
Views: 60378
Reputation: 3826
You can find the available inline options here:
https://learn.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-options
At the top table, the column inline character shows the recognized option. You either wrap the part of the regex where the regex should be applied inside. In general you use:
(?options) ... (?-options). You can combine multiple inline options here, options can be for example 'ix' where 'x' is IgnorePatternWhitespace .
For example: (?i)Tim(?-i) corey
Matches :
"Tim corey" but not "Tim Corey" since only Tim here is case insensitive. "tim corey" also matches. (I am following a Regex video tutorial by Tim Corey right now and he uses his name all the time in examples, so I am also using his name here).
Upvotes: 0
Reputation: 12103
(?i)
within the pattern begins case-insensitive matching, (?-i)
ends it. That is,
(?i)foo(?-i)bar
matches FOObar
, fOobar
and foobar
but not fooBAR
.
EDIT: I should have said (?-i)
starts case-sensitive matching - if you want the whole pattern to be case-insensitive then you don't need to "end" the (?i)
.
Upvotes: 169