Following on from this question I asked yesterday:
Can I shorten this regular expression?
The solution was to use the following expression:
^([a-z]{5}-){4}[a-z]{5}$
To check for a match for a string with the following format:
aBcDe-fghIj-KLmno-pQRsT-uVWxy
I was advised to omit the A-Z from my original query and make the Regular Expression case insensitive in the code that uses it. For example, specify RegExOptions.IgnoreCase in the constructor for the RegEx in C#.
Is there any reason why this should be done in code rather than the regular expression itself?
I think this question is valid enough to warrant a new question rather than continuing the discussion in yesterday’s.
There is no absolutely correct answer to this question. There are several ways to achieve certain things, and which is best is sometimes subjective. Besides, the two ways aren’t exactly identical to begin with.
It should be noted that a regex pattern can in fact be partially case-insensitive. That is, you can have a pattern that is case insensitive in one part, but case sensitive in other parts.
Perhaps a good guideline is the following:
Do note that there is in fact a big difference between these two patterns:
Both patterns match
"FOO-FOO"and"bar-bar", but the first pattern matches"BOO-boo"(as seen on rubular.com). The second pattern does not (as seen on rubular.com).See also
/regex/i(Pattern.CASE_INSENSITIVEin Java), you can do/(?i)regex//first(?i)second(?-i)third//first(?i:second)third/Related questions