使用正则表达式或其他方法将 C# 字符串拆分为 3 个单词块

Splitting C# string into 3 word chunks using regex or other method

我想制作一个功能,可以将 C# 中的字符串分成 3 个单词块,如下所示:

Today is a nice day, and I have been driving a car /*(don't laugh lol - not a part of sentence)*/

所以我想做的第一件事就是从字符串中删除除数字和字母之外的所有特殊字符。

一旦我这样做了,然后将单词分成 3 个单词块,其中上句的输出将是:

Today is a 
nice day and
I have been
driving a car

我想通过正则表达式来做到这一点,但又一次有 LINQ 方法和所有可以轻松解决这个问题的方法,所以我不太确定选择哪种方式来实现这个?什么是最有效的方法?

P.S。我正在考虑的另一个问题是,如果一个词有 8 个词,而我想将它分成 3 个块词……?我将如何丢弃最后两个不符合形成 3 个块的标准的单词 "sentence"?

有人可以帮我吗?

string str = "Today is a nice day, and I have been driving a car";

str =  Regex.Replace(str, "[^0-9a-zA-Z ]+", "");

string[] arr = str.Split(' ');
int nElements = 0;

for (int i = 0; i < arr.Length; i+=3)
{
    if(i+3 < arr.Length)
    {
        nElements = 3;
    }
    else
    {
        nElements = arr.Length - i;
    }

    Console.WriteLine(arr.Skip(i).Take(nElements).Aggregate((current, next) => current + " " + next));
}

使用正则表达式 ([a-zA-Z]+) 获取所有单词,然后将其放入数组并从中构建 3 个单词块到数组或列表中。 如果你有 8 个单词,你可以检查数组是否可以除以 3,如果不是只删除最后两个或一个单词。代码如下所示:

        string str = "Today is a nice day, and I have been driving a car";
        Regex r = new Regex("[a-zA-Z]+", RegexOptions.IgnoreCase);
        var wordCollection = r.Matches(str).Cast<Match>().Select(m => m.Value).ToList();

        var number = wordCollection.Count % 3;
        if (number == 1)
        {
            wordCollection.RemoveAt(wordCollection.Count - 1);
        }
        else if (number == 2)
        {
            wordCollection.RemoveAt(wordCollection.Count - 1);
            wordCollection.RemoveAt(wordCollection.Count - number - 1);
        }

        var list = new List<string>();
        for (var i = 0; i < wordCollection.Count; i+=3)
        {
            list.Add(string.Format("{0} {1} {2}", wordCollection[i], wordCollection[i + 1], wordCollection[i + 2]));

        }

编辑: 添加 howManyToRemove 变量以检查我是否需要删除一个或两个单词。

编辑 2: 我的代码中有一个小错误,我修复了它。

我认为这是一种最原始的方法:
你应该用“”分割你的输入字符串,这是通过使用 string.Split() 函数完成的,如果没有传递参数,它会用白色 space 分割。
现在你应该只传递你从 split 中得到的数组并取 3 个元素。
要从元素中删除特殊符号,您可以使用以下 RegEx 模式 [^a-zA-Z0-9],其中 ^ - 表示查找 [].

中未指定的任何元素
string a = "Today is a nice day, and I have been driving";
var res = a.Split();
List<string> groups = new List<string>();
Regex rgx = new Regex("[^a-zA-Z0-9]");
for (int i=0;i< res.Length;i+=3)
{
    string result = string.Empty;
    try
    {
        result += rgx.Replace(res[i], ""); 
    }
    catch(Exception)
    {

    }
    try
    {
        result +=" "+ rgx.Replace(res[i+1], ""); ;
    }
    catch (Exception)
    {
        groups.Add(result);
        break;
    }
    try
    {
        result +=" "+ rgx.Replace(res[i + 2], ""); 
    }
    catch (Exception)
    {
        groups.Add(result);
        break;
    }
    groups.Add(result);
}
foreach(var a1 in groups)
{
    Console.WriteLine(a1);
}