如何用 C# 找到字串中的數字?


如需在字串中找到數字,請使用正則表示式。

我們已經設定了正則表示式模式,以從字串中獲取數字。

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

更新於:2020 年 6 月 22 日

305 次瀏覽

開啟您的 職業

透過完成課程獲得認證

開始
廣告