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

Viết Regex chỉ chấp nhận số (Numbers only) trong C#

Sử dụng System.Text.RegularExpressions.Regex để validate chuỗi chỉ chứa chữ số.

Pattern cơ bản

Yêu cầuRegex PatternGiải thích
Chỉ số nguyên dương (1 hoặc nhiều chữ số)^\d+$ hoặc ^[0-9]+$^ đầu, $ cuối, \d = [0-9], + = 1 hoặc nhiều
Số nguyên (có dấu +/-)^[-+]?\d+$[-+]? dấu tùy chọn
Số thực (có phần thập phân)^[-+]?\d*\.?\d+$Cho phép .5, 5., 5.0
Số thực chuẩn (có ít nhất 1 chữ số trước/sau dấu chấm)^[-+]?\d+(\.\d+)?$Bắt buộc có chữ số
Chỉ số, cho phép phân cách nghìn (1,000)^\d{1,3}(,\d{3})*$US format

Ví dụ hoàn chỉnh


using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string[] tests = { "123", "123.45", "-10", "+5", "abc", "12a3", "", "0", "007" };
        string pattern = @"^-?\d+(\.\d+)?$"; // Số thực có dấu, optional decimal
        
        Regex regex = new Regex(pattern, RegexOptions.Compiled); // Compiled cho performance
        
        foreach (string test in tests)
        {
            bool match = regex.IsMatch(test);
            Console.WriteLine($"'{test}' -> {match}");
        }
        Console.ReadLine();
    }
}

Kết quả


'123' -> True
'123.45' -> True
'-10' -> True
'+5' -> False (pattern không có +)
'abc' -> False
'12a3' -> False
'' -> False
'0' -> True
'007' -> True

Extension Method tiện lợi


public static class StringExtensions
{
    private static readonly Regex _intRegex = new(@"^\d+$", RegexOptions.Compiled);
    private static readonly Regex _decimalRegex = new(@"^\d+(\.\d+)?$", RegexOptions.Compiled);
    
    public static bool IsInteger(this string s) => !string.IsNullOrEmpty(s) && _intRegex.IsMatch(s);
    public static bool IsDecimal(this string s) => !string.IsNullOrEmpty(s) && _decimalRegex.IsMatch(s);
    
    // Parse an toàn
    public static int? ToIntOrNull(this string s) => s.IsInteger() ? int.Parse(s) : null;
    public static decimal? ToDecimalOrNull(this string s) => s.IsDecimal() ? decimal.Parse(s) : null;
}

// Usage
Console.WriteLine("123".IsInteger());    // True
Console.WriteLine("12.3".IsInteger());   // False
Console.WriteLine("12.3".IsDecimal());   // True
Console.WriteLine("abc".ToIntOrNull());  // null

Lưu ý hiệu suất

  • Dùng RegexOptions.Compiled cho pattern dùng nhiều lần (cache compiled regex).
  • Static readonly Regex instance để tránh compile lại mỗi lần.
  • Với validation đơn giản (chỉ digit), char.IsDigit hoặc int.TryParse nhanh hơn Regex.

So sánh TryParse vs Regex


// Nhanh nhất cho int
bool isInt = int.TryParse(s, out _);

// Nhanh nhất cho decimal
bool isDec = decimal.TryParse(s, out _);

// Regex chỉ khi cần pattern phức tạp (format cụ thể, range, v.v.)