Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Cách tìm và trích xuất số từ chuỗi trong C#

Regular expression là pattern có thể match với input text. .NET framework cung cấp regex engine cho phép matching như vậy. Pattern bao gồm một hoặc nhiều character literals, operators, hoặc constructs.

Các basic pattern metacharacters dùng bởi RegEx:

* = zero or more
? = zero or one
^ = not
[] = range

Symbol ^ dùng để specify not condition. Dùng [] brackets cho range values như 0-9, a-z, A-Z.

Dùng Char.IsDigit()

Ví dụ

using System; 

namespace DemoApplication { 
    public class Program { 
        static void Main(string[] args) { 
            string str1 = "123string456"; 
            string str2 = string.Empty; 
            int val = 0; 
            Console.WriteLine($"String with number: {str1}"); 
            
            for (int i = 0; i < str1.Length; i++) { 
                if (Char.IsDigit(str1[i])) 
                    str2 += str1[i]; 
            } 
            
            if (str2.Length > 0) 
                val = int.Parse(str2); 
            Console.WriteLine($"Extracted Number: {val}"); 
            Console.ReadLine(); 
        } 
    } 
}

Output

String with number: 123string456
Extracted Number: 123456

Trong ví dụ trên loop qua tất cả characters của string str1. Char.IsDigit() validate character có phải số không và thêm vào string mới, sau đó parse thành number.

Dùng Regex

Ví dụ

using System; 
using System.Text.RegularExpressions; 

namespace DemoApplication { 
    public class Program { 
        static void Main(string[] args) { 
            string str1 = "123string456"; 
            string str2 = string.Empty; 
            int val = 0; 
            Console.WriteLine($"String with number: {str1}"); 
            
            var matches = Regex.Matches(str1, @"\d+"); 
            foreach (var match in matches) { 
                str2 += match; 
            } 
            val = int.Parse(str2); 
            Console.WriteLine($"Extracted Number: {val}"); 
            Console.ReadLine(); 
        } 
    } 
}

Output

String with number: 123string456
Extracted Number: 123456

Trong ví dụ trên, dùng regular expression (\d+) để trích xuất chỉ numbers từ string str1.

Các Pattern Regex phổ biến cho số

Pattern Mô tả Ví dụ match
\d+ Một hoặc nhiều chữ số (0-9) 123, 45, 0
\d* Zero hoặc nhiều chữ số "", 123, 45
\d{3} Chính xác 3 chữ số 123, 456
\d{1,3} 1 đến 3 chữ số 1, 12, 123
[-+]?\d+ Số có dấu +/- tùy chọn -123, +45, 67
[-+]?\d*\.?\d+ Số thực (decimal) 3.14, -0.5, +2.0
[-+]?\d+(\.\d+)? Số nguyên hoặc thực 123, 3.14, -5

Các phương pháp khác

1. LINQ (Where + Char.IsDigit)

string numbersOnly = new string(str1.Where(Char.IsDigit).ToArray());
// "123456"

2. StringBuilder (hiệu quả hơn cho string lớn)

var sb = new StringBuilder();
foreach (char c in str1) {
    if (Char.IsDigit(c)) sb.Append(c);
}
string numbersOnly = sb.ToString();

3. Chỉ lấy số đầu tiên (First number)

var firstNumber = Regex.Match(str1, @"\d+").Value; // "123"
int firstNum = int.Parse(firstNumber);

4. Lấy tất cả số riêng biệt (tách biệt)

var numbers = Regex.Matches(str1, @"\d+")
    .Cast()
    .Select(m => int.Parse(m.Value))
    .ToList(); // [123, 456]

5. Parse số có dấu và decimal

string input = "Price: -$1,234.56";
var match = Regex.Match(input, @"[-+]?\d*\.?\d+");
if (match.Success) {
    double price = double.Parse(match.Value, NumberStyles.AllowCurrencySymbol | NumberStyles.AllowThousands);
    // price = -1234.56
}

Performance Tips

  • Compile Regex nếu dùng lặp lại: static readonly Regex _digitRegex = new Regex(@"\d+", RegexOptions.Compiled);
  • Char.IsDigit nhanh hơn Regex cho việc đơn giản
  • StringBuilder tốt hơn string concatenation trong loop
  • Span và Memory cho high-performance parsing (.NET Core 2.1+)