首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 正則表達式驗證工具類:Email、電話、IP、日期、郵編、中文等常用模式整理

     編輯:關於C語言

驗證工具類完整程式碼


using System;
using System.Text.RegularExpressions;

public static class RegexValidator {
    // 編譯選項:忽略大小寫 + 編譯優化(首次較慢,後續極快)
    private static readonly RegexOptions Options = RegexOptions.IgnoreCase | RegexOptions.Compiled;

    // ===== 常用驗證方法 =====

    /// Email 格式驗證(RFC 5322 簡化版)
    public static bool IsValidEmail(string input) {
        if (string.IsNullOrWhiteSpace(input)) return false;
        const string pattern = @"^[\w\.-]+@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
        return Regex.IsMatch(input, pattern, Options);
    }

    /// 手機/市話號碼(大陸格式:區號-號碼、11位手機)
    public static bool IsValidPhone(string input) {
        if (string.IsNullOrWhiteSpace(input)) return false;
        const string pattern = @"^(\d{3,4}-)?\d{7,8}(-\d+)?$|^1[3-9]\d{9}$";
        return Regex.IsMatch(input, pattern, Options);
    }

    /// IPv4 位址
    public static bool IsValidIPv4(string input) {
        if (string.IsNullOrWhiteSpace(input)) return false;
        const string pattern = @"^((25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)$";
        return Regex.IsMatch(input, pattern, Options);
    }

    /// 日期時間:yyyy-MM-dd HH:mm:ss
    public static bool IsValidDateTime(string input) {
        if (string.IsNullOrWhiteSpace(input)) return false;
        const string pattern = @"^2\d{3}-(?:0?[1-9]|1[0-2])-(?:0?[1-9]|[12]\d|3[01])(?:[01]?\d|2[0-3]):(?:[0-5]?\d):(?:[0-5]?\d)$";
        return Regex.IsMatch(input, pattern, Options);
    }

    /// 身分證字號(台灣格式:1字母+9數字)
    public static bool IsValidTWId(string input) {
        if (string.IsNullOrWhiteSpace(input)) return false;
        const string pattern = @"^[A-Z][12]\d{8}$";
        return Regex.IsMatch(input, pattern, Options);
    }

    /// 中文字串(含標點)
    public static bool IsChinese(string input) {
        if (string.IsNullOrWhiteSpace(input)) return false;
        const string pattern = @"^[\u4e00-\u9fa5\u3000-\u303f\uff00-\uffef]+$";
        return Regex.IsMatch(input, pattern, Options);
    }

    /// 英數字底線 4-12 位(帳號常用)
    public static bool IsAlnumUnderscore_4_12(string input) {
        if (string.IsNullOrWhiteSpace(input)) return false;
        const string pattern = @"^[a-zA-Z0-9_]{4,12}$";
        return Regex.IsMatch(input, pattern, Options);
    }

    /// 小數:0.00~1.00 或 0~1 兩位小數
    public static bool IsDecimal_0_1(string input) {
        if (string.IsNullOrWhiteSpace(input)) return false;
        const string pattern = @"^(0(\.\d{1,2})?|1(\.0{1,2})?)$";
        return Regex.IsMatch(input, pattern, Options);
    }

    /// 圖片副檔名
    public static bool IsImageExtension(string fileName) {
        if (string.IsNullOrWhiteSpace(fileName)) return false;
        const string pattern = @"\.(jpg|jpeg|png|gif|bmp|webp)$";
        return Regex.IsMatch(fileName, pattern, Options);
    }

    /// 提取 HTML 中所有 href 連結
    public static string[] ExtractHrefs(string html) {
        if (string.IsNullOrWhiteSpace(html)) return Array.Empty();
        const string pattern = @"href\s*=\s*[""'](?[^""']+)[""']";
        var matches = Regex.Matches(html, pattern, Options);
        var urls = new string[matches.Count];
        for (int i = 0; i < matches.Count; i++) urls[i] = matches[i].Groups["url"].Value;
        return urls;
    }

    /// 日期格式轉換:MM/dd/yyyy → dd-MM-yyyy
    public static string ConvertUsDateToEuro(string input) {
        if (string.IsNullOrWhiteSpace(input)) return input;
        return Regex.Replace(input, @"\b(?\d{1,2})/(?\d{1,2})/(?\d{2,4})\b", "${day}-${month}-${year}");
    }
}

使用範例


string email = "test@example.com";
string phone = "02-12345678";
string ip = "192.168.1.1";
string date = "2024-12-31 23:59:59";

Console.WriteLine($"Email: {RegexValidator.IsValidEmail(email)}");
Console.WriteLine($"Phone: {RegexValidator.IsValidPhone(phone)}");
Console.WriteLine($"IPv4:  {RegexValidator.IsValidIPv4(ip)}");
Console.WriteLine($"Date:  {RegexValidator.IsValidDateTime(date)}");

// 提取連結
string html = "AB";
foreach (var url in RegexValidator.ExtractHrefs(html)) Console.WriteLine(url);

// 日期轉換
Console.WriteLine(RegexValidator.ConvertUsDateToEuro("12/31/2024")); // 31-12-2024

正則效能優化關鍵

  1. RegexOptions.Compiled:將模式編譯為 IL,首次較慢但後續執行極快,適合重複呼叫的驗證方法。
  2. 靜態唯讀欄位:模式字串與 Regex 實例化為 `static readonly`,避免重複編譯。
  3. 避免過度回溯:慎用巢狀量詞 `(a+)+`、貪婪 `.*`,改用非貪婪 `.*?` 或定長 `\d{4}`。
  4. 使用具名群組:`(?...)` 提高可讀性與維護性。
  5. 預先驗證長度/空值:`string.IsNullOrWhiteSpace` 快速攔截,避免正則引擎啟動。

進階:.NET 7+ Regex Generator(原始碼產生器)


// 專案檔啟用 enable latest
using System.Text.RegularExpressions;

public partial class MyRegex {
    [GeneratedRegex(@"^[\w\.-]+@([\w-]+\.)+[\w-]{2,}$", RegexOptions.IgnoreCase | RegexOptions.Compiled)]
    public static partial Regex EmailRegex { get; }
}

// 使用:MyRegex.EmailRegex().IsMatch(input)
// 優點:AOT 友善、零反射、編譯期檢查模式語法、效能最優

常見正則陷阱

錯誤寫法問題修正
`\w` 匹配中文`\w` 僅 `[a-zA-Z0-9_]`用 `[\u4e00-\u9fa5\w]`
`.*` 貪婪匹配整行回溯災難用 `.*?` 或 `[^""]*`
未轉義 `.` `(` `)` `[` `]`被視為元字元用 `\.` `\(` `\)` `\[` `\]`
`^$` 在多行模式錯誤單行模式僅匹配字串首尾加 `RegexOptions.Multiline`
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved