C# Regex Match between with or without new lines

后端 未结 2 1392
一向
一向 2021-01-19 17:06

I am trying to match text between two delimiters, [% %], and I want to get everything whether the string contains new lines or not.

Code

2条回答
  •  一个人的身影
    2021-01-19 17:36

    To get text between two delimiters you need to use lazy matching with .*?, but to also match newline symbols, you need (?s) singleline modifier so that the dot could also match newline symbols:

    (?s)\[%(.*?)%]
    

    Note that (?s)\[%(.*?)%] will match even if the % is inside [%...%].

    See regex demo. Note that the ] does not have to be escaped since it is situated in an unambiguous position and can only be interpreted as a literal ].

    In C#, you can use

    var rx = new Regex(@"(?s)\[%(.*?)%]");
    var res = rx.Matches(str).Cast().Select(p => p.Groups[1].Value).ToList();
    

提交回复
热议问题