C#正则表达式与用法

发布于:2025-09-01 ⋅ 阅读:(15) ⋅ 点赞:(0)

🌟 C# 常用正则表达式与用法

C# 使用正则需要引用命名空间:


using System.Text.RegularExpressions;

常用方法:

  • Regex.IsMatch(input, pattern) → 返回 bool,用于验证

  • Regex.Match(input, pattern) → 返回 Match 对象,可获取捕获内容

  • Regex.Matches(input, pattern) → 返回 MatchCollection,获取所有匹配

  • Regex.Replace(input, pattern, replacement) → 替换字符串


1. 验证类示例


// 手机号验证 bool isPhone = Regex.IsMatch("13812345678", @"^1[3-9]\d{9}$"); // 邮箱验证 bool isEmail = Regex.IsMatch("txj@example.com", @"^[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}$"); // 身份证验证 bool isID = Regex.IsMatch("110105199001011234", @"^\d{17}[\dXx]$"); // IP 地址验证 bool isIP = Regex.IsMatch("192.168.0.1", @"^(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)){3}$"); // 强密码验证(8-20位,字母+数字) bool isStrongPwd = Regex.IsMatch("Txj123456", @"^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,20}$");


2. 提取类示例


// 提取数字 string text = "订单号123456"; MatchCollection nums = Regex.Matches(text, @"\d+"); foreach (Match m in nums) Console.WriteLine(m.Value); // 输出 123456 // 提取邮箱用户名 string email = "txj@example.com"; Match userMatch = Regex.Match(email, @"^([\w.-]+)@"); if(userMatch.Success) Console.WriteLine(userMatch.Groups[1].Value); // 输出 txj // 提取 URL 域名 string url = "https://www.txj.com/path"; Match urlMatch = Regex.Match(url, @"https?://([\w.-]+)"); if(urlMatch.Success) Console.WriteLine(urlMatch.Groups[1].Value); // 输出 www.txj.com


3. 替换类示例


// 去掉首尾空格 string str = " hello world "; string clean = Regex.Replace(str, @"^\s+|\s+$", ""); Console.WriteLine(clean); // hello world // 替换 HTML 标签 string html = "<p>hello</p>"; string plain = Regex.Replace(html, @"<[^>]+>", ""); Console.WriteLine(plain); // hello


4. 常用正则大全(C# 版)

用途 正则表达式 说明
手机号 ^1[3-9]\d{9}$ 中国大陆手机号
邮箱 ^[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}$ 邮箱格式
身份证 ^\d{17}[\dXx]$ 18位身份证
IP 地址 `^(25[0-5] 2[0-4]\d
URL 域名 https?://([\w.-]+) 提取主机名
日期 ^\d{4}-\d{2}-\d{2}$ YYYY-MM-DD
数字 \d+ 提取数字
银行卡号 ^\d{16,19}$ 16~19位数字
强密码 ^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,20}$ 字母+数字组合
中文字符 ^[\u4e00-\u9fa5]+$ 全中文
HTML 标签 <([a-z]+)[^>]*>(.*?)</\1> 捕获标签内容
时间 HH:MM:SS `^([01]\d 2[0-3]):[0-5]\d:[0-5]\d$`
十六进制颜色 `^#?([a-fA-F0-9]{6} [a-fA-F0-9]{3})$`

网站公告

今日签到

点亮在社区的每一天
去签到