查找某个字符串中的所有数字时,我们可以先将所有数字存储到一个字符串数组中,然后通过遍历数组的方式查找出字符串中的所有数字,接下来济南网站建设小编来为大家介绍另一种方法,通过正则表达式方式来获取字符串中的所有数字,有需要的朋可以过来参考一下。
关键代码:
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
class Program
{
static void Main()
{
string input = "这里输入你的包含数字的字符串, 例如: abc123def456ghi789";
// 使用正则表达式匹配数字
MatchCollection matches = Regex.Matches(input, @"\d+");
List<string> numbers = new List<string>();
foreach (Match match in matches)
{
// 将找到的每一个数字添加到列表中
numbers.Add(match.Value);
Console.WriteLine("找到数字: " + match.Value);
}
// 如果需要进一步处理这些数字,请在此进行
}
}
评论