如何用 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP