6

我需要将此字符串拆分"hello1\r\nhello2\r\n\r\nhello3\r\n\r\n\r\nhello4" 为:{"hello1\r\nhello2" , "hello3", "hello4"}

我的代码:

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

结果是:{"hello1\r\nhello2" ,"\r\n" , "hello3" ,"\r\n" ,"hello4"}

我究竟做错了什么?

4

1 回答 1

8

你很亲密。只需使用非捕获组:

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

Regex.Split将捕获的组添加到结果数组中,如Regex.Split的“备注”部分中所述。

于 2012-11-09T17:10:03.080 回答