簡體   English   中英

如何使用正則表達式從字符串中獲取數值

[英]How to get the numeric value from a string using regular expression

如何使用正則表達式從以下字符串中獲取數值

   AD  .6547 BNM

結果應該是

 .6547
var src = "AD  .6547 BNM";

var match = Regex.Match(input, @"(\.\d+)");
if (match.Success) {
    var result = match.Groups[1].Value;
}

我通常會從Regex.Match開始。 如果要解析多個字符串,則通過實例化Regex對象並使用Matches實例方法而不是使用靜態Match方法,將獲得一點好處。 這只是一個小好處,但是...

如果您對性能有很大的擔憂,並且輸入字符串的格式是靜態的,則您甚至可以考慮放棄正則表達式,而使用string.Substring甚至是string.Split。 您的問題促使我衡量以下幾種不同方法之間的性能差異。

static void TestParse()
    {
        List<string> strList = new List<string>
        {
            "AD  .1234 BNM", 
            "AD  .6547 BNM", 
            "AD  .6557 BNM", 
            "AD  .6567 BNM", 
            "AD  .6577 BNM", 
            "AD  .6587 BNM", 
            "AD  .6597 BNM", 
            "AD  .6540 BNM", 
            "AD  .6541 BNM", 
            "AD  .6542 BNM"
        };

        Stopwatch stopwatch = new Stopwatch();
        string result = "";
        stopwatch.Start();
        for (int i=0; i<100000; i++)
            foreach (string str in strList)
            {
                var match = Regex.Match(str, @"(\.\d+)");
                if (match.Success)
                    result = match.Groups[1].Value;
            }
        stopwatch.Stop();
        Console.WriteLine("\nTotal Regex.Match time 1000000 parses: {0}", stopwatch.ElapsedMilliseconds);

        result = "";
        stopwatch.Reset();
        stopwatch.Start();
        Regex exp = new Regex(@"(\.\d+)", RegexOptions.IgnoreCase);
        for (int i = 0; i < 100000; i++)
            foreach (string str in strList)
                result = exp.Matches(str)[0].Value;
        stopwatch.Stop();
        Console.WriteLine("Total Regex object time 1000000 parses: {0}", stopwatch.ElapsedMilliseconds);

        result = "";
        stopwatch.Reset();
        stopwatch.Start();
        for (int i = 0; i < 100000; i++)
            foreach (string str in strList)
                result = str.Substring(4, 5);
        stopwatch.Stop();
        Console.WriteLine("Total string.Substring time 1000000 parses: {0}", stopwatch.ElapsedMilliseconds);

        result = "";
        stopwatch.Reset();
        stopwatch.Start();
        char[] seps = { ' ' };
        for (int i = 0; i < 100000; i++)
            foreach (string str in strList)
                result = str.Split(seps, StringSplitOptions.RemoveEmptyEntries)[1];
        stopwatch.Stop();
        Console.WriteLine("Total string.Split time 1000000 parses: {0}", stopwatch.ElapsedMilliseconds);
    }
\.\d+

應該做到這一點和一些C#代碼:

Regex exp = new Regex(
    @"(\.\d+)",
    RegexOptions.IgnoreCase);

string InputText = "AD .1234";
MatchCollection MatchList = exp.Matches(InputText);
Match FirstMatch = MatchList[0];
string value = MatchList[0].value;

嘗試

\.\d*

它將選擇“。” 及其后的所有數字。

暫無
暫無

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

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