C# Regex Match between with or without new lines

后端 未结 2 1362
一向
一向 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<Match>().Select(p => p.Groups[1].Value).ToList();
    
    0 讨论(0)
  • 2021-01-19 17:39

    Try this pattern:

    \[%([^%]*)%\]
    

    It captures all characters between "[%" and "%]" that is not a "%" character.

    Tested @ Regex101

    If you want to "see" the "\r\n" in your results, you'll have to escape them with a String.Replace().

    See Fiddle Demo

    0 讨论(0)
提交回复
热议问题