萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

C# 通用正則驗證工具類:內建 25 種常用模式與自定義匹配

類設計目標

  • 封裝常見數據格式驗證(郵箱、手機、身份證、IP、URL 等)
  • 支持「完全匹配」與「包含匹配」兩種模式
  • 提供枚舉類型選擇驗證規則,擴展性強
  • 可獲取所有匹配項,不僅是布爾判斷

完整類代碼

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace Xrinehart.Framework.Common.Validate
{
    /// 
    /// 正則表達式驗證工具類
    /// 
    public class RegularMatch
    {
        private string _input;
        private bool _isEntirety;

        /// 
        /// 內建驗證類型枚舉
        /// 
        public enum Operation
        {
            // 基礎類型
            Byte, SByte, Int16, Int32, Int64, Single, Double, Boolean, Char, Decimal,
            DateTime, Date, Time,
            // 格式類型
            EMail, URL, ChinaPhone, ChineseWord, ChinesePostalCode, Number,
            StringModel_01, StringModel_02, WideWord, NarrowWord, IPAddress,
            ChineseMobile, ChineseID
        };

        /// 
        /// 默認包含匹配模式
        /// 
        public bool IsAccordType(string input, Operation op)
            => IsAccordType(input, op, false);

        /// 
        /// 指定匹配模式
        /// 
        /// 待驗證字符串
        /// 驗證類型
        /// true=完全匹配, false=包含匹配
        public bool IsAccordType(string input, Operation op, bool isEntirety)
        {
            _input = input;
            _isEntirety = isEntirety;

            return op switch
            {
                Operation.Byte        => IsByte(),
                Operation.SByte       => IsSByte(),
                Operation.Int16       => IsInt16(),
                Operation.Int32       => IsInt32(),
                Operation.Int64       => IsInt64(),
                Operation.Single      => IsSingle(),
                Operation.Double      => IsDouble(),
                Operation.Boolean     => IsBoolean(),
                Operation.Char        => IsChar(),
                Operation.Decimal     => IsDecimal(),
                Operation.DateTime    => IsDateTime(),
                Operation.Date        => IsDate(),
                Operation.Time        => IsTime(),
                Operation.IPAddress   => IsIPAddress(),
                Operation.ChinaPhone  => IsChinaPhone(),
                Operation.ChinesePostalCode => IsChinesePostalCode(),
                Operation.ChineseMobile => IsChineseMobile(),
                Operation.EMail       => IsEmail(),
                Operation.URL         => IsURL(),
                Operation.ChineseWord => IsChineseWord(),
                Operation.Number      => IsNumber(),
                Operation.StringModel_01 => IsStringModel_01(),
                Operation.StringModel_02 => IsStringModel_02(),
                Operation.WideWord    => IsWideWord(),
                Operation.NarrowWord  => IsNarrowWord(),
                Operation.ChineseID   => IsChineseID(),
                _ => false
            };
        }

        #region 基礎類型驗證 (TryParse 模式)
        private bool IsByte() => byte.TryParse(_input, out _);
        private bool IsSByte() => sbyte.TryParse(_input, out _);
        private bool IsInt16() => short.TryParse(_input, out _);
        private bool IsInt32() => int.TryParse(_input, out _);
        private bool IsInt64() => long.TryParse(_input, out _);
        private bool IsSingle() => float.TryParse(_input, out _);
        private bool IsDouble() => double.TryParse(_input, out _);
        private bool IsBoolean() => bool.TryParse(_input, out _);
        private bool IsChar() => char.TryParse(_input, out _);
        private bool IsDecimal() => decimal.TryParse(_input, out _);
        #endregion

        #region 日期時間驗證
        private bool IsDateTime() => DateTime.TryParse(_input, out _);
        private bool IsDate() => DateTime.TryParseExact(_input, "yyyy-MM-dd", null, System.Globalization.DateTimeStyles.None, out _);
        private bool IsTime() => DateTime.TryParseExact(_input, "HH:mm:ss", null, System.Globalization.DateTimeStyles.None, out _);
        #endregion

        #region 正則驗證方法
        private bool IsIPAddress() => Match(@"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        private bool IsChinaPhone() => Match(@"^(0\d{2,3}-)?\d{7,8}$");
        private bool IsChinesePostalCode() => Match(@"^\d{6}$");
        private bool IsChineseMobile() => Match(@"^1[3-9]\d{9}$");
        private bool IsEmail() => Match(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
        private bool IsURL() => Match(@"^(https?|ftp)://[^\s/$.?#].[^\s]*$");
        private bool IsChineseWord() => Match(@"^[\u4e00-\u9fa5]+$");
        private bool IsNumber() => Match(@"^-?\d+(\.\d+)?$");
        private bool IsStringModel_01() => Match(@"^[a-zA-Z0-9_]{4,20}$"); // 用戶名模式
        private bool IsStringModel_02() => Match(@"^[\w\-\.]+@([\w-]+\.)+[\w-]{2,4}$"); // 同 Email
        private bool IsWideWord() => Match(@"^[\uFF00-\uFFFF]+$"); // 全角字符
        private bool IsNarrowWord() => Match(@"^[\u0020-\u007E]+$"); // 半角字符
        private bool IsChineseID() => Match(@"^\d{17}[\dXx]$"); // 18位身份證(簡易版)
        #endregion

        /// 
        /// 核心匹配邏輯
        /// 
        private bool Match(string pattern)
        {
            if (string.IsNullOrEmpty(_input)) return false;

            string regexPattern = _isEntirety ? $"^{pattern}$" : pattern;
            return Regex.IsMatch(_input, regexPattern, RegexOptions.IgnoreCase);
        }

        /// 
        /// 獲取所有匹配項
        /// 
        public MatchCollection GetMatches(string pattern)
        {
            return Regex.Matches(_input ?? "", pattern, RegexOptions.IgnoreCase);
        }
    }
}

使用示例

var validator = new RegularMatch();

// 1. 完全匹配驗證手機號
bool valid = validator.IsAccordType("13812345678", RegularMatch.Operation.ChineseMobile, true);
// valid = true

// 2. 包含匹配提取郵箱
var matches = validator.GetMatches(@"[\w-\.]+@([\w-]+\.)+[\w-]{2,4}");
foreach (Match m in matches) {
    Console.WriteLine(m.Value); // 輸出所有郵箱
}

// 3. 驗證身份證 (簡易版)
bool idValid = validator.IsAccordType("11010119900307123X", RegularMatch.Operation.ChineseID, true);

// 4. 基礎類型驗證
bool isInt = validator.IsAccordType("12345", RegularMatch.Operation.Int32); // true
bool isDecimal = validator.IsAccordType("12.34", RegularMatch.Operation.Decimal); // true

擴展指南

  1. 添加新枚舉值:在 Operation 中增加 CustomPattern
  2. 實現對應方法:private bool IsCustomPattern() => Match(@"你的正則");
  3. 在 switch 中添加 case

注意事項

  • 身份證驗證僅做格式校驗,真實項目需結合校驗碼算法、地址碼庫、出生日期邏輯
  • 郵箱正則為常用簡化版,RFC 5322 完整正則極其複雜,通常不建議生產環境使用
  • 大量高頻調用時,建議預編譯 Regex 對象或使用 RegexOptions.Compiled

總結

該類將 25 種常見驗證規則封裝為枚舉驅動的統一入口,代碼結構清晰、易於維護擴展。核心 Match() 方法統一處理「完全/包含」匹配邏輯,GetMatches() 提供提取能力。實際項目中可作為基礎驗證層,配合 FluentValidation 或 DataAnnotations 構建完整驗證體系。

copyright © 萬盛學電腦網 all rights reserved