如何在长字符串中找到所有以'$'开头并以空格结尾的单词?

时间:2010-10-21 11:53:26

标签: c# regex string

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

3 个答案:

答案 0 :(得分:9)

尝试:

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

在上文中,\\w匹配单词字符。这些是A-Z,a-z, - 和_如果我是正确的。如果您想匹配不是空格的所有内容,可以使用\\S。如果您需要特定的设置,请通过以下方式指定: [a-zA-Z0-9]

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

作为一个完整的例子:

string input = "$a1 $a2 $b1 $b2";

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

这会产生以下输出:

$a1
$a2
$b1

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

答案 1 :(得分:5)

你可以尝试没有正则表达式,这可能会更快。

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

编辑: 在Zain Shaikh的评论之后,我写了一个简单的程序进行基准测试,结果就是这里。

        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)比正则表达式函数更快;)

答案 2 :(得分:0)

var a1 = "fdjksf $jgjkd $hfj".Split(" ".ToCharArray())
                                     .ToList()
                                     .Where(X=>Regex.Match(X , "(\\$[a-zA-Z]*)").Success);