簡體   English   中英

如何在長字符串中找到所有以'$'開頭並以空格結尾的單詞?

[英]How to find all the words starting with '$' sign and ending with space, in a long string?

在C#中,如何使用正則表達式在長字符串中找到所有以'$'符號開頭並以空格結尾的單詞?

嘗試:

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

在上面, \\\\w匹配單詞字符。 這些是AZ,az, - 和_如果我是正確的。 如果要匹配不是空格的所有內容,可以使用\\\\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當然被省略,因為它沒有尾隨空格。

您可以在沒有正則表達式的情況下嘗試它,這可能會更快。

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)比正則表達式函數更快;)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM