简体   繁体   English

从字符串中提取所有数字

[英]Extract all numbers from string

Let's say I have a string such as 123ad456 .假设我有一个字符串,例如123ad456 I want to make a method that separates the groups of numbers into a list, so then the output will be something like 123,456 .我想制作一种将数字组分成一个列表的方法,因此输出将类似于123,456

I've tried doing return Regex.Match(str, @"-?\\d+").Value;我试过做return Regex.Match(str, @"-?\\d+").Value; , but that only outputs the first occurrence of a number, so the output would be 123 . ,但这仅输出数字的第一次出现,因此输出将是123 I also know I can use Regex.Matches , but from my understanding, that would output 123456 , not separating the different groups of numbers.我也知道我可以使用Regex.Matches ,但根据我的理解,这将输出123456 ,而不是将不同的数字组分开。

I also see from this page on MSDN that Regex.Match has an overload that takes the string to find a match for and an int as an index at which to search for the match, but I don't see an overload that takes in the above in addition to a parameter for the regex pattern to search for, and the same goes for Regex.Matches .我还从 MSDN 上的这个页面看到Regex.Match有一个重载,它使用string来查找匹配项和一个int作为搜索匹配项的索引,但我没有看到一个重载上面除了要搜索的正则表达式模式的参数之外,同样适用于Regex.Matches

I guess the approach to use would be to use a for loop of some sort, but I'm not entirely sure what to do.我想使用的方法是使用某种for循环,但我不完全确定该怎么做。 Help would be greatly appreciated.帮助将不胜感激。

All you have to to use Matches instead of Match .所有你必须使用Matches而不是Match Then simply iterate over all matches:然后简单地遍历所有匹配项:

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

You may iterate over string data using foreach and use TryParse to check each character.您可以使用 foreach 遍历字符串数据并使用TryParse来检查每个字符。

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

Using a combination of string.Join and Regex.Matches :使用string.JoinRegex.Matches的组合:

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

string.Join performs better than continually appending to an existing string. string.Join性能比不断追加到现有字符串要好。

\\d+ is the regex for integer numbers; \\d+ 是整数的正则表达式;

//System.Text.RegularExpressions.Regex resultString = Regex.Match(subjectString, @"\\d+").Value; //System.Text.RegularExpressions.Regex resultString = Regex.Match(subjectString, @"\\d+").Value; returns a string with the very first occurence of a number in subjectString.返回一个字符串,其中一个数字在 subjectString 中第一次出现。

Int32.Parse(resultString) will then give you the number. Int32.Parse(resultString) 然后会给你这个数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM