如何在 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+ 瀏覽量

啟動你的 職業生涯

完成課程並獲得認證

開始
廣告