Để khớp tất cả các chữ số trong một chuỗi, hãy sử dụng C # Regex.
Đầu tiên, đặt một chuỗi có các chữ số -
string str = "These are my marks: 90 out of 100!";
Sử dụng biểu thức chính quy sau để nhận các chữ số trong một chuỗi -
@"\d+"
Sau đây là mã -
Ví 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(); } } }
Đầu ra
Getting digits from a string... The Expression: \d+ 90 100