如何使用内联修饰符在C#中的正则表达式? [英] How to use inline modifiers in C# regex?
问题描述
我如何使用内联改性剂代替 RegexOptions.Option
?
How do I use the inline modifiers instead of RegexOptions.Option
?
例如:
Regex MyRegex = new Regex(@"[a-z]+", RegexOptions.IgnoreCase);
如何使用在线角色我重写这个我
?
<一个href="http://msdn.microsoft.com/en-us/library/yd1hzczs.aspx">http://msdn.microsoft.com/en-us/library/yd1hzczs.aspx
推荐答案
您可以使用内联修饰符如下:
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]+");
和一组括号,这作用域修改为只:
另外,你可以使用一个冒号使用的模式修改跨度的语法组:
// case sensitive, then case-insensitive match
Regex MyRegex = new Regex(@"(?-i:[a-z]+)(?i:[k-n]+)");
您可以一次过这样的使用多个修饰符(是-M:文本)
,还是层出不穷,如果你发现更加清晰 (?I)(S?)( - M)文本
(我不知道)。当您使用开/关语法,请注意修改工作,直到下一个开关,或正则表达式的结束。相反,使用模式修饰的跨度,跨度后的默认行为将适用。
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.
最后:允许改性剂.NET是(使用负反转模式):
Finally: the allowed modifiers in .NET are (use a minus to invert the mode):
X
允许空白和注释
取值
单线模式
M
多行模式
我
不区分大小写
N
只允许明确捕获(.NET专用)
x
allow whitespace and comments
s
single line mode
m
multi line mode
i
case insensitivity
n
only allow explicit capture (.NET specific)
这篇关于如何使用内联修饰符在C#中的正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!