正则表达式来打破字符串C#

时间:2011-10-22 07:54:59

标签: c# regex

这是我的字符串:

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.

3 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分: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将匹配项放入{{1}}。

答案 2 :(得分:0)

行将以换行符,回车符或两者结束。这会将字符串拆分为包含所有行结尾的行。

using System.Text.RegularExpressions;

...

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

然后你可以用每一行做你想做的事。

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