如何在 C# 中编写仅匹配数字的正则表达式?


正则表达式是一种可以与输入文本匹配的模式。

.Net 框架提供了一个正则表达式引擎,允许进行这种匹配。

一种模式由一个或多个字符文本、运算符或结构组成。

以下是由 RegEx 使用的基本模式元字符:−

* = zero or more
? = zero or one
^ = not
[] = range

^ 符号用于指定非条件。

如果我们给予值域,例如 0-9 或 a-z 或 A-Z,则使用 [] 括号

示例

class Program{
   public static void Main(){
      string num = "123dh";
      Regex regex = new Regex(@"^-?[0-9][0-9,\.]+$");
      var res = regex.IsMatch(num);
      System.Console.WriteLine(res);
   }
}

输出

False

示例

class Program{
   public static void Main(){
      string num = "123";
      Regex regex = new Regex(@"^-?[0-9][0-9,\.]+$");
      var res = regex.IsMatch(num);
      System.Console.WriteLine(res);
   }
}

输出

True

示例

class Program{
   public static void Main(){
      string num = "123.67";
      Regex regex = new Regex(@"^-?[0-9][0-9,\.]+$");
      var res = regex.IsMatch(num);
      System.Console.WriteLine(res);
   }
}

输出

True

更新于: 2020 年 9 月 25 日

3K+ 浏览量

启动你的 职业生涯

完成课程并获得认证

开始
广告
© . All rights reserved.