C # Regex Matching with or without newlines

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

the code

 string strEmailContent = sr.ReadToEnd(); string commentPatt = @"\[%((\r\n?|\n).*(\r\n?|\n))%\]"; Regex commentRgx = new Regex(commentPatt, RegexOptions.Singleline); 

Input Examples

 //Successful [% New Comment %] other content from input //Match: [%\r\nNew Comment\r\n%] //Fail [% New Comment %] //Match: false //Successfully match single line with string commentPatt = @"\[%(.*)%\]"; //Match: [% New Comment %] 

I do not know how to combine these two patterns according to both cases. Can anyone help?

+4
source share
2 answers

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

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

Please note that (?s)\[%(.*?)%] Will match even if % is inside [%...%] .

See the demo version of regex . Please note that ] does not need to be escaped since it is in the unique 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(); 
+1
source

Try this template:

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

It captures all characters between " [% " and " %] ", which is not the character " % ".

Tested @ Regex101

If you want to "see" " \r\n " in your results, you will have to escape using String.Replace() .

See Demo Screenshot

+1
source

All Articles