ใช้ Regex.Matches กับ Pattern \d+ (ตัวเลข 1 หลักขึ้นไป) เพื่อหาตัวเลขทุกกลุ่มในสตริง
ตัวอย่างโค้ด
using System;
using System.Text.RegularExpressions;
namespace Demo
{
class Program
{
private static void ShowMatch(string text, string expr)
{
Console.WriteLine("The Expression: " + expr);
MatchCollection mc = Regex.Matches(text, expr);
foreach (Match m in mc) Console.WriteLine(m);
}
static void Main(string[] args)
{
string str = "These are my marks: 90 out of 100!";
Console.WriteLine("Getting digits from a string...");
ShowMatch(str, @"\d+");
}
}
}
ผลลัพธ์
Getting digits from a string... The Expression: \d+ 90 100
Pattern อื่น: \d (ตัวเลข 1 หลัก), \d{3} (ตัวเลข 3 หลักพอดี)