Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split by double or more empty lines? Regex.Stplit adds unwanted strings

Tags:

string

c#

regex

I need to split this string: "hello1\r\nhello2\r\n\r\nhello3\r\n\r\n\r\nhello4" to: {"hello1\r\nhello2" , "hello3", "hello4"}

my code:

string text = "hello1\r\nhello2\r\n\r\nhello3\r\n\r\n\r\nhello4"; 
string[] wordsarray = Regex.Split(text, @"(\r\n){2,}");

The result is: {"hello1\r\nhello2" ,"\r\n" , "hello3" ,"\r\n" ,"hello4"}

What am I doing wrong?

like image 786
Mikaèl Avatar asked Nov 09 '12 17:11

Mikaèl


People also ask

How do you split a string by the occurrences of a regex pattern?

split() method split the string by the occurrences of the regex pattern, returning a list containing the resulting substrings.

What happens if you split an empty string?

If the delimiter is an empty string, the split() method will return an array of elements, one element for each character of string. If you specify an empty string for string, the split() method will return an empty string and not an array of strings.

Does split modify the original string?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

Can we use regex in split a string?

split(String regex) method splits this string around matches of the given regular expression. This method works in the same way as invoking the method i.e split(String regex, int limit) with the given expression and a limit argument of zero. Therefore, trailing empty strings are not included in the resulting array.


1 Answers

You are very close. Simply use a non-capturing group:

Regex.Split(text, @"(?:\r\n){2,}")

Regex.Split adds captured groups to the result array as described in "Remarks" section of Regex.Split.

like image 96
Kobi Avatar answered Oct 11 '22 14:10

Kobi