正则表达式验证

    xiaoxiao2021-03-25  106

    using System;

    using System.Text; using System.Text.RegularExpressions; namespace Test { /// <summary> /// 正则表达式扩展 /// </summary> public static class RegexExpressions { /// <summary> /// 电子邮件 /// </summary> public static bool EmailRegex(this string input) { string patternRegex = @"[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?"; return RegexAll(input, patternRegex); } /// <summary> /// Url /// </summary> public static bool UrlRegex(this string input) { string patternRegex = @"[a-zA-z]+://[^\s]*"; return RegexAll(input, patternRegex); } /// <summary> /// 电话号码 /// </summary> public static bool TellPhoneRegex(this string input) { string patternRegex = @"\d{3}-\d{8}|\d{4}-\{7,8}"; return RegexAll(input, patternRegex); } /// <summary> /// QQ号码 /// </summary> public static bool QQRegex(this string input) { string patternRegex = @"[1-9][0-9]{4,}"; return RegexAll(input, patternRegex); } /// <summary> /// 身份证号码 /// </summary> public static bool IdentityCardRegex(this string input) { string patternRegex = @"^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$"; return RegexAll(input, patternRegex); } /// <summary> /// 正则表达式验证规则 /// </summary> /// <param name="input">明文</param> /// <param name="patternRegex">验证规则</param> private static bool RegexAll(string input, string patternRegex) { bool isOK = false; try { isOK = new Regex(patternRegex, RegexOptions.IgnoreCase).Match(input).Success; } catch (ArgumentNullException) { return false; } catch (ArgumentOutOfRangeException) { return false; } catch (ArgumentException) { return false; } catch (RegexMatchTimeoutException) { return false; } catch (Exception) { return false; } return isOK; } } }
    转载请注明原文地址: https://ju.6miu.com/read-21531.html

    最新回复(0)