C# 如何使正则表达式匹配不区分大小写?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11965524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make a regex match case insensitive?
提问by khurram
I have following regular expression for postal code of Canada.
我有以下加拿大邮政编码的正则表达式。
^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$
It is working fine but accepts only Capital letters. I want it work for both capital and small letters.
它工作正常,但只接受大写字母。我希望它适用于大写和小写字母。
回答by stema
Just use the option IgnoreCase, see .NET regular Expression Options
只需使用该选项IgnoreCase,请参阅.NET 正则表达式选项
So your regex creation could look like this
所以你的正则表达式创建可能看起来像这样
Regex r = new Regex(@"^[ABCEGHJKLMNPRSTVXY]\d[A-Z] *\d[A-Z]\d$", RegexOptions.IgnoreCase);
I removed also all your {1}because it is superfluous. Every item is per default matched once, no need to state this explicitly.
我也删除了你的所有内容,{1}因为它是多余的。每个项目默认匹配一次,无需明确说明。
The other possibility would be to use inline modifiers, when you are not able to set it on the object.
另一种可能性是使用内联修饰符,当您无法在对象上设置它时。
^(?i)[ABCEGHJKLMNPRSTVXY]\d[A-Z] *\d[A-Z]\d$

