How to use inline modifiers in C# regex?

后端 未结 2 830
心在旅途
心在旅途 2020-12-01 18:19

How do I use the inline modifiers instead of RegexOptions.Option?

For example:

Regex MyRegex = new Regex(@\"[a-z]+\", RegexOptions.Igno         


        
2条回答
  •  离开以前
    2020-12-01 18:48

    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]+");
    

    Alternatively, you can use the mode-modifier span syntax using a colon : and a grouping parenthesis, which scopes the modifier to only that group:

    // case sensitive, then case-insensitive match
    Regex MyRegex = new Regex(@"(?-i:[a-z]+)(?i:[k-n]+)");
    

    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.

    Finally: the allowed modifiers in .NET are (use a minus to invert the mode):

    x allow whitespace and comments
    s single-line mode
    m multi-line mode
    i case insensitivity
    n only allow explicit capture (.NET specific)

提交回复
热议问题