简体   繁体   中英

Extract all numbers from string

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.

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;
}

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
    }
}

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.

\\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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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