หากต้องการจับคู่ตัวเลขทั้งหมดในสตริง ให้ใช้ C# Regex
ขั้นแรก ตั้งค่าสตริงที่มีตัวเลข −
string str = "These are my marks: 90 out of 100!";
ใช้นิพจน์ทั่วไปต่อไปนี้เพื่อรับตัวเลขในสตริง -
@"\d+"
ต่อไปนี้เป็นรหัส −
ตัวอย่าง
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+");
Console.ReadKey();
}
}
} ผลลัพธ์
Getting digits from a string... The Expression: \d+ 90 100