Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex replace multiple new lines

Tags:

c#

regex

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
like image 522
Deeptechtons Avatar asked Dec 02 '16 13:12

Deeptechtons


1 Answers

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,}
like image 54
Wiktor Stribiżew Avatar answered Oct 22 '22 14:10

Wiktor Stribiżew