Sử dụng Regex.Matches với mẫu \d+ (một hoặc nhiều chữ số) để trích xuất tất cả số trong chuỗi.
Ví dụ
using System;
using System.Text.RegularExpressions;
namespace Demo
{
class Program
{
private static void ShowMatch(string text, string expr)
{
Console.WriteLine("Biểu thức: " + 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("Lấy chữ số từ chuỗi...");
ShowMatch(str, @"\d+");
Console.ReadKey();
}
}
}
Kết quả
Lấy chữ số từ chuỗi... Biểu thức: \d+ 90 100