拆分字符串并使用Regex和C#添加到列表

时间:2012-08-09 08:02:01

标签: c# regex string

我有一个字符串,其中的字数可能会有所不同。像:

string a_string = " one two three four five six seven etc etc etc "; 

如何将字符串分成5个单词,并将每个字符串添加到列表中,使其成为字符串列表(每个字符串包含5个单词)。我认为列表会更好,因为字符串中的单词数量可能会有所不同,因此列表可以相应地增大或缩小。

我尝试使用Regex通过以下代码行获得前5个单词:

Regex.Match(rawMessage, @"(\w+\s+){5}").ToString().Trim();

但有点不确定如何进一步继续并动态地添加到列表中。我猜Regex可以进一步提供帮助,还是一些很棒的字符串/列表功能?你能指点一下吗?

最终,我希望list [0]包含“one two three four five”,列表[1]包含“six seven etc etc etc”,依此类推......谢谢。

3 个答案:

答案 0 :(得分:4)

var listOfWords = Regex.Matches(a_string, @"(\w+\s+){1,5}")
     .Cast<Match>()
     .Select(i => i.Value.Trim())
     .ToList();

答案 1 :(得分:1)

分词不需要正则表达式,字符串提供此功能:

var list = str.Split(' ').ToList();

ToList()是一个LINQ扩展方法,用于将IEnumerable<T>个对象转换为列表(Split()方法返回一个字符串数组。)

要按5个字对列表进行分组,请使用以下代码段:

var res = list
    .Select((s, i) => new { Str = s, Index = i })
    .GroupBy(p => p.Index/5)
    .Select(g => string.Join(" ", g.Select(v => v.Str)));

答案 2 :(得分:0)

您可以使用简单的

a_string.Split(' ');

然后遍历生成的数组并根据需要填充列表,例如

int numOfWords = 0;
int currentPosition = 0;
foreach (var str in a_string.Split(' '))
{
   if (numOfWords == 5)
   {
     numOfWords = 0;
     currentPosition++;
   }
   list[currentPosition] += str;
   numOfWords++;
}
相关问题