Extract all numbers from string

大憨熊 提交于 2020-06-23 12:18:26

问题


Let's say I have a string such as 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.

I've tried doing return Regex.Match(str, @"-?\d+").Value;, but that only outputs the first occurrence of a number, so the output would be 123. I also know I can use Regex.Matches, but from my understanding, that would output 123456, not separating the different groups of numbers.

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.

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. Help would be greatly appreciated.


回答1:


All you have to to use Matches instead of Match. Then simply iterate over all matches:

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



回答2:


You may iterate over string data using foreach and use TryParse to check each character.

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



回答3:


Using a combination of string.Join and Regex.Matches:

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

string.Join performs better than continually appending to an existing string.




回答4:


\d+ is the regex for integer numbers;

//System.Text.RegularExpressions.Regex resultString = Regex.Match(subjectString, @"\d+").Value; returns a string with the very first occurence of a number in subjectString.

Int32.Parse(resultString) will then give you the number.



来源:https://stackoverflow.com/questions/52581241/extract-all-numbers-from-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!