问题
regexp are not my strong point but I have a list of 4 strings that I want to check for. I created a pattern which is readable(to me) so more can be added easily but I am 99% sure none will be.
The list is, and I want to match the string regardless of what case is used.
- packstation - ( packstation | Packstation | PACKSTATION )
- pack station - ( pack station | Pack station | pack Station | Pack Station | PACK STATION )
- paketstation - ( paketstation | Paketstation | PAKETSTATION )
- paket station - ( paket station | Paket station| paket Station| Paket Station | PAKET STATION )
The pattern I am using is
^(?!packstation|pack station|paketstation|paket station$).*$
My problem is I am unable to ignore case. I have tried adding the i flag in multiple places but it just breaks the pattern recognition and nothing gets through.
Not sure if I need to create a more complex pattern or if its a problem with Demandware's regexp which just accepts a pattern.
回答1:
You didn't indicate the language. If you are using Java, Python, Ruby, Perl, .NET, or PCRE (PHP), you can tack on an internal modifier (?i)
to your pattern. In your case:
(?i)^(?!packstation|pack station|paketstation|paket station$).*$
Well you can also shorten it to:
(?i)^(?!pack ?station|paket ?station$).*$
For this case, the regex will have the same effect in all the languages listed above.
Note that the regex will reject:
packstation
PackStation
PACKSTATION
pAcKstAtioN
All combination of uppercase/lowercase letters will be rejected.
In Python, internal modifier is global, and you can only turn it on for the whole pattern (regardless of the position where you declare it).
In Java, Ruby, Perl, .NET or PCRE, you can scope the internal modifier by using it in a non-capturing group (?modifiers:pattern)
. You can also turn it on from the specified position with (?modifiers)
and turn it off from the specified position with (?-modifiers)
, since in these languages, the effect of the modifiers are scoped to the position where it is declared.
Usually, most languages will give you an option to specify the flags outside the main pattern. It may support it as the trailing characters after the closing delimiter to the main pattern, or it may support it in the function call.
来源:https://stackoverflow.com/questions/16809700/ignoring-case-for-a-whole-pattern-of-strings