将字符串拆分为字符串生成器,删除所有与模式匹配的单词

本文关键字:字符串 单词 删除 模式匹配 拆分 | 更新日期: 2023-09-27 18:33:23

我有一串用([ ''t{}():;.,،'"'n])分隔的单词。如何将该字符串拆分为StringBuilder,同时删除与模式匹配的任何单词@"'d|'s|/|-"并删除长度小于 2 个字符的所有单词。最后,我想将其存储回字符串中。

Regex r = new Regex("([ ''t{}():;.,،'"'n])");
    String[] tokens = r.Split(sb.ToString());
    List<string> filter = new List<string>();
    for (int i = 0; i < tokens.Length; i++)
    {
        ........................
        {
            .....................
        }

    }
    ................
    return builder.ToString();

将字符串拆分为字符串生成器,删除所有与模式匹配的单词

我想出了这个。它与您的解决方案没有太大区别,除了我使用 LINQ 并完全避免使用 StringBuidler。你能接受吗?

using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
class Program {
    static void Main(string[] args) {
        string value = "one or:another{3}";
        Regex exclude = new Regex(@"'d|'s|/|-", RegexOptions.Compiled);
        string final = string.Join(" ",
            (from s in Regex.Split(value, "([ ''t{}():;.,،'"'n])")
                where s.Length > 2 && !exclude.IsMatch(s)
                select s.Replace("ه‌","ه")).ToArray());
        // to get the List<string> instead:
        List<string> l = (from s in Regex.Split(value, "([ ''t{}():;.,،'"'n])")
            where s.Length > 2 && !exclude.IsMatch(s)
            select s.Replace("ه‌","ه")).ToList();
    }
}

代码对我来说看起来不错。 正则表达式处理确实需要很长时间。 也许尝试在顶部创建@"'d's|/|-"Regex m = new Regex(@"''d''s|/|-");,以避免在每圈重新解析它。