代码之家  ›  专栏  ›  技术社区  ›  Zain Shaikh

如何在长字符串中查找以“$”符号开头、以空格结尾的所有单词?

  •  5
  • Zain Shaikh  · 技术社区  · 14 年前

    在C中,如何使用正则表达式在长字符串中查找以“$”符号开头、以空格结尾的所有单词?

    3 回复  |  直到 14 年前
        1
  •  9
  •   Pieter van Ginkel    14 年前

    尝试:

    var matches = Regex.Matches(input, "(\\$\\w+) ");
    

    在上面, \\w 匹配单词字符。这些是A-Z,A-Z,-如果我是对的话。如果你想匹配所有不是空格的东西,你可以使用 \\S . 如果需要特定的集合,请通过例如 [a-zA-Z0-9] .

    括号围绕 (\\$\\w+) 确保特定匹配, matches[0].Groups[1].Value; 给出了backets中的值(因此,不包括尾随空格)。

    作为一个完整的例子:

    string input = "$a1 $a2 $b1 $b2";
    
    foreach (Match match in Regex.Matches(input, "(\\$\\w+) "))
    {
        Console.WriteLine(match.Groups[1].Value);
    }
    

    这将产生以下输出:

    $a1
    $a2
    $b1
    

    $b2当然被省略了,因为它没有尾随空格。

        2
  •  5
  •   Peter Mortensen icecrime    14 年前

    您可以在不使用正则表达式的情况下进行尝试,这可能会更快。

    string longText = "";
        List<string> found = new List<string>();
        foreach (var item in longText.Split(' '))
        {
            if (item.StartsWith("$"))
            {
                found.Add(item);
            }
        }
    

    编辑: 在ZainShaikh的评论之后,我写了一个简单的程序来进行基准测试,结果如下。

            string input = "$a1 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2";
            var s1 = Stopwatch.StartNew();
            double first;
            foreach (Match match in Regex.Matches(input, "(\\$\\w+) "))
            {
            }
            s1.Stop();
            Console.WriteLine(" 1) " + (s1.Elapsed.TotalMilliseconds * 1000 * 1000).ToString("0.00 ns"));
            first = s1.Elapsed.TotalMilliseconds;
            s1.Reset();
    
            s1 = Stopwatch.StartNew();
    
            foreach (var item in input.Split(' '))
            {
                if (item.StartsWith("$"))
                {
                }
            }
            s1.Stop();
            Console.WriteLine(" 2) " + (s1.Elapsed.TotalMilliseconds * 1000 * 1000).ToString("0.00 ns"));
            Console.WriteLine(s1.Elapsed.TotalMilliseconds - first);
    

    输出:

    1) 730600.00 ns
    
    2)  53000.00 ns
    
    -0.6776
    

    这意味着字符串函数(也有foreach)比正则表达式函数更快;)

        3
  •  0
  •   Thorin Oakenshield    14 年前
    var a1 = "fdjksf $jgjkd $hfj".Split(" ".ToCharArray())
                                         .ToList()
                                         .Where(X=>Regex.Match(X , "(\\$[a-zA-Z]*)").Success);