可以使用正则表达式来提取文本中的数字。以下是一个示例代码:

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main(string[] args)
    {
        string text = "abc 123 def 456";

        // 使用正则表达式提取第一组数字
        Match match = Regex.Match(text, @"\d+");

        if (match.Success)
        {
            string firstNumber = match.Value;
            Console.WriteLine("第一组数字为:" + firstNumber);
        }
        else
        {
            Console.WriteLine("文本中没有找到数字");
        }
    }
}

上述代码将输出第一组数字 "123"。如果文本中没有数字,则输出 "文本中没有找到数字"

C# 文本中取数字只取第一组数字

原文地址: http://www.cveoy.top/t/topic/it9G 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录