簡體   English   中英

從字符串中提取所有數字

[英]Extract all numbers from string

假設我有一個字符串,例如123ad456 我想制作一種將數字組分成一個列表的方法,因此輸出將類似於123,456

我試過做return Regex.Match(str, @"-?\\d+").Value; ,但這僅輸出數字的第一次出現,因此輸出將是123 我也知道我可以使用Regex.Matches ,但根據我的理解,這將輸出123456 ,而不是將不同的數字組分開。

我還從 MSDN 上的這個頁面看到Regex.Match有一個重載,它使用string來查找匹配項和一個int作為搜索匹配項的索引,但我沒有看到一個重載上面除了要搜索的正則表達式模式的參數之外,同樣適用於Regex.Matches

我想使用的方法是使用某種for循環,但我不完全確定該怎么做。 幫助將不勝感激。

所有你必須使用Matches而不是Match 然后簡單地遍歷所有匹配項:

string result = "";
foreach (Match match in Regex.Matches(str, @"-?\d+"))
{
    result += match.result;
}

您可以使用 foreach 遍歷字符串數據並使用TryParse來檢查每個字符。

foreach (var item in stringData)
{
    if (int.TryParse(item.ToString(), out int data))
    {
        // int data is contained in variable data
    }
}

使用string.JoinRegex.Matches的組合:

string result = string.Join(",", Regex.Matches(str, @"-?\d+").Select(m => m.Value));

string.Join性能比不斷追加到現有字符串要好。

\\d+ 是整數的正則表達式;

//System.Text.RegularExpressions.Regex resultString = Regex.Match(subjectString, @"\\d+").Value; 返回一個字符串,其中一個數字在 subjectString 中第一次出現。

Int32.Parse(resultString) 然后會給你這個數字。

暫無
暫無

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

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