หากต้องการค้นหาตัวเลขในสตริง ให้ใช้นิพจน์ทั่วไป
เราได้ตั้งค่ารูปแบบ Regex เพื่อรับตัวเลขจากสตริง
Regex r = new Regex(@"\d+");
ตอนนี้ ใช้คลาส Match ใน C# เพื่อตั้งค่าสตริง
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