假设我有一个字符串,例如 123ad456.我想制作一种将数字组分成一个列表的方法,因此输出将类似于 123,456.
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.
我试过做 return Regex.Match(str, @"-?\d+").Value;,但它只输出一个数字的第一次出现,所以输出将是 123.我也知道我可以使用 Regex.Matches,但根据我的理解,这会输出 123456,而不是将不同的数字组分开.
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.
我还从 this 页面,Regex.Match 有一个重载,它使用 string 来找到一个 int 作为搜索匹配项的索引,但除了要搜索的正则表达式模式的参数之外,我没有看到上面的重载,Regex 也是如此.匹配.
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.
我想使用的方法是使用某种 for 循环,但我不完全确定该怎么做.不胜感激.
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.
推荐答案所有你必须使用 Matches 而不是 Match.然后简单地遍历所有匹配项:
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; }更多推荐
从字符串中提取所有数字
发布评论