2011-10-22 48 views
2

这里是我的字符串:正则表达式打破字符串C#

1-1 This is my first string. 1-2 This is my second string. 1-3 This is my third string. 

我怎样才能打破像C#一样;

result[0] = This is my first string. 
result[1] = This is my second string. 
result[2] = This is my third string. 

回答

5
IEnumerable<string> lines = Regex.Split(text, "(?:^|[\r\n]+)[0-9-]+ ").Skip(1); 

编辑:如果你想在数组中的结果,你可以做string[] result = lines.ToArray();

+0

+1非常漂亮的使用Split + ^跳过 – xanatos

+0

这个逻辑不起作用... – fawad

+0

@fawad我用你的示例字符串测试过它。检查你的代码。 –

0

线将与换行,回车或两个端,该拆分字符串与所有行结束线。

using System.Text.RegularExpressions; 

... 

var lines = Regex.Split(input, "[\r\n]+"); 

然后,你可以做你想要的每一行。

var words = Regex.Split(line[i], "\s"); 
+0

行结束是不可能的,但我想从1-1,1-2和1-3分裂。 – fawad

2
Regex regex = new Regex("^(?:[0-9]+-[0-9]+)(.*?)$", RegexOptions.Multiline); 

var str = "1-1 This is my first string.\n1-2 This is my second string.\n1-3 This is my third string."; 

var matches = regex.Matches(str); 

List<string> strings = matches.Cast<Match>().Select(p => p.Groups[1].Value).ToList(); 

foreach (var s in strings) 
{ 
    Console.WriteLine(s); 
} 

我们使用正则表达式多,所以^$是开始和行结束。我们跳过一个或多个数字,一个-,一个或多个数字和一个空格(?:[0-9]+-[0-9]+)。我们懒洋洋地(*?)采取一切(.)否则,直到行(.*?)$结束后,懒洋洋地使该行$的到底是比任何字符.

然后更“重要”我们把比赛的List<string>使用LINQ。