从字符串中提取所有数字

编程入门 行业动态 更新时间:2024-10-19 19:52:06
本文介绍了从字符串中提取所有数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有一个字符串,例如 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; }

更多推荐

从字符串中提取所有数字

本文发布于:2023-06-13 17:40:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/686676.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!