In C# how do i specify regex to replace multiple groups. For example i would like to replace more than one instance of either \r\n
or \r\r
with a environment newline. I logically wrote this regex , but i know it is wrong. Please correct and explain how it works.
System.Text.RegularExpressions.Regex.Replace(task.Message, @"(\r\n){2,}(\r\r){2,}", System.Environment.NewLine);
Input text
Stackoverflow
StackExchange
User Experience
Where each line may be separated either by \r\n
or \r\r
. Expected outcome after regex replace is below
Stackoverflow
StackExchange
User Experience
The point is that your regex matches sequences of \r\n
(2 or more) and then 2 or more sequences of \r\r
. You need
[\r\n]+
Or [\r\n]{2,}
if you need to only match 2 or more occurrences of \r
or \n
.
If you need to exactly match 2 or more common line break types (\r\n
in Windows, \n
in Unix/Linux and \r
on Mac OS), use
(?:\r?\n|\r){2,}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With