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?
split() method split the string by the occurrences of the regex pattern, returning a list containing the resulting substrings.
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.
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.
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.
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.
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