怎么查找字符串中所有的数字?-c# 编程小实例

济南云服务器 2025年3月24日06:10:04C#教程怎么查找字符串中所有的数字?-c# 编程小实例已关闭评论43阅读模式

查找某个字符串中的所有数字时,我们可以先将所有数字存储到一个字符串数组中,然后通过遍历数组的方式查找出字符串中的所有数字,接下来济南网站建设小编来为大家介绍另一种方法,通过正则表达式方式来获取字符串中的所有数字,有需要的朋可以过来参考一下。

关键代码:

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

        // 如果需要进一步处理这些数字,请在此进行
    }
}

济南云服务器
  • 本文由 发表于 2025年3月24日06:10:04
  • 转载请务必保留本文链接:http://news.hcsw666.com/2045