如何在 C# 中查找字符串中的数字?

csharpprogrammingserver side programming更新于 2025/5/27 0:52:17

要在字符串中查找数字,请使用正则表达式。

我们已设置正则表达式模式以从字符串中获取数字。

Regex r = new Regex(@"\d+");

现在,使用 C# 中的 Match 类设置字符串。

Match m = r.Match("Welcome! We are open 365 days in a year!");

现在使用 Success 属性显示结果(如果在字符串中找到数字),如以下完整代码所示 −

示例

using System;
using System.Text.RegularExpressions;

class Demo {
   static void Main() {

      Regex r = new Regex(@"\d+");
      Match m = r.Match("Welcome! We are open 365 days in a year!");

      if (m.Success) {
         Console.Write("Number: ");
         Console.WriteLine(m.Value);
      }
   }
}

输出

Number: 365

相关文章