I am trying to match text between two delimiters, [% %]
, and I want to get everything whether the string contains new lines or not.
Code
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();
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