正则表达式(Regular Expression,简称 Regex )是一种用于匹配、查找、替换字符串 的规则。在 C# 中,正则表达式由 System.Text.RegularExpressions 命名空间提供。
掌握 Regex 后,可以轻松完成:
- ✔ 验证手机号
- ✔ 验证邮箱
- ✔ 提取数字
- ✔ 查找指定字符串
- ✔ 批量替换文本
- ✔ 分割字符串
- ✔ 解析日志
- ✔ 数据清洗
一、命名空间
using System.Text.RegularExpressions;
二、Regex 类
最常用的是 Regex 类。
常见方法:
| 方法 | 作用 |
|---|---|
| IsMatch() | 是否匹配 |
| Match() | 获取第一个匹配 |
| Matches() | 获取所有匹配 |
| Replace() | 替换字符串 |
| Split() | 分割字符串 |
| Escape() | 转义特殊字符 |
| Unescape() | 取消转义 |
三、最简单的例子
判断字符串中是否包含数字。
cs
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string str = "abc123";
bool result = Regex.IsMatch(str, @"\d");
Console.WriteLine(result);
}
}
输出
True
因为:
\d
表示数字。
四、Regex.IsMatch()
用于判断是否符合规则。
语法:
cs
Regex.IsMatch(字符串, 正则表达式)
例如:
cs
string phone = "13812345678";
bool result = Regex.IsMatch(phone, @"^1\d{10}$");
Console.WriteLine(result);
输出
True
解释:
^
开始
1
第一位必须是1
\d
数字
{10}
后面10位
$
结束
五、Regex.Match()
返回第一个匹配结果。
例如:
cs
string str = "abc123xyz456";
Match match = Regex.Match(str, @"\d+");
Console.WriteLine(match.Value);
输出
123
说明:
\d+
表示:
一个或多个数字。
Match 常用属性
match.Value
匹配内容
match.Index
开始位置
match.Length
长度
例如:
cs
Console.WriteLine(match.Value);
Console.WriteLine(match.Index);
Console.WriteLine(match.Length);
输出:
123
3
3
六、Regex.Matches()
获取所有匹配。
例如:
cs
string str = "abc123xyz456aaa789";
MatchCollection mc = Regex.Matches(str, @"\d+");
foreach (Match item in mc)
{
Console.WriteLine(item.Value);
}
输出:
123
456
789
七、Regex.Replace()
替换。
例如:
把所有数字替换成 *
cs
string str = "abc123xyz456";
string result = Regex.Replace(str, @"\d", "*");
Console.WriteLine(result);
输出
abc***xyz***
替换整个数字
cs
string result = Regex.Replace(str, @"\d+", "***");
输出
abc***xyz***
八、Regex.Split()
按规则切割。
例如:
cs
string str = "张三,李四;王五|赵六";
string[] arr = Regex.Split(str, @"[,;|]");
foreach (string s in arr)
{
Console.WriteLine(s);
}
输出
张三
李四
王五
赵六
九、常用元字符
1、匹配任意字符(除换行)。
Regex.IsMatch("abc", "a.c")
结果:
True
2、\d
数字
0~9
例如:
123
3、\D
非数字
abc
4、\w
字母
数字
下划线
即:
A-Z
a-z
0-9
_
5、\W
非单词字符。
6、\s
空白字符。
包括:
空格
Tab
换行
7、\S
非空白。
8、^
开始
例如:
^abc
必须以 abc 开头。
9、$
结束
abc$
必须以 abc 结尾。
10、\[\]
字符集合。
例如:
[abc]
匹配:
a
b
c
例如:
Regex.IsMatch("apple", "[abc]")
结果:
True
11、\^
取反
[^0-9]
不是数字。
12、|
或者
cat|dog
匹配
cat
dog
十、数量词
*
0 次或多次
ab*
可以匹配:
a
ab
abb
abbb
+
1 次或多次
ab+
匹配:
ab
abb
?
0 次或1次
colou?r
匹配:
color
colour
{n}
指定次数
\d{6}
6 位数字。
{m,n}
范围
\d{6,10}
6~10 位数字。
{m,}
至少 m 次
a{3,}
至少三个 a。
十一、分组 ()
例如:
cs
string str = "2026-07-10";
Match m = Regex.Match(str,
@"(\d{4})-(\d{2})-(\d{2})");
Console.WriteLine(m.Groups[1].Value);
Console.WriteLine(m.Groups[2].Value);
Console.WriteLine(m.Groups[3].Value);
输出
2026
07
10
Groups:
0
整个匹配
1
第一组
2
第二组
十二、常见验证
手机号
@"^1\d{10}$"
邮箱
@"^[\w.-]+@[\w.-]+\.[A-Za-z]{2,}$"
身份证(18位,基础格式)
@"^\d{17}[\dXx]$"
该表达式只校验基本格式,不校验行政区划、出生日期或校验码。
@"^[1-9]\d{4,10}$"
用户名
6~20 位
字母数字下划线
@"^\w{6,20}$"
密码
8~20 位
必须包含大小写字母和数字
@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,20}$"
十三、RegexOptions(匹配选项)
cs
Regex.IsMatch(
"ABC",
"abc",
RegexOptions.IgnoreCase);
常见选项:
| 选项 | 说明 |
|---|---|
| IgnoreCase | 忽略大小写 |
| Multiline | 多行模式(^、$ 匹配每行) |
| Singleline | 单行模式(. 可匹配换行) |
| Compiled | 编译正则,提高重复使用性能(首次创建开销略高) |
| CultureInvariant | 与区域性无关的匹配 |
十四、逐字字符串(@)
建议写正则时使用:
@"\d+"
而不是
"\\d+"
这样无需对反斜杠进行二次转义,可读性更高。
十五、实战案例
1. 提取所有邮箱
cs
string text = @"
tom@test.com
jack@qq.com
abc@163.com";
MatchCollection mc = Regex.Matches(
text,
@"[\w.-]+@[\w.-]+\.[A-Za-z]{2,}");
foreach (Match m in mc)
{
Console.WriteLine(m.Value);
}
输出:
tom@test.com
jack@qq.com
abc@163.com
2. 隐藏手机号中间四位
cs
string phone = "13812345678";
string result = Regex.Replace(
phone,
@"(\d{3})\d{4}(\d{4})",
"$1****$2");
Console.WriteLine(result);
输出:
138****5678
3. 删除所有 HTML 标签
cs
string html = "<p>Hello <b>World</b></p>";
string text = Regex.Replace(html, "<.*?>", "");
Console.WriteLine(text);
输出:
Hello World
注意: 对于复杂 HTML,不建议使用正则解析,应使用专门的 HTML 解析库(如 Html Agility Pack)。
十六、学习建议
建议按以下顺序掌握正则表达式:
- 基础语法 :字符、字符集、数量词、锚点(
^、$)。 - Regex 常用方法 :
IsMatch()、Match()、Matches()、Replace()、Split()。 - 进阶特性:分组、命名分组、反向引用、零宽断言(前瞻/后顾)、贪婪与懒惰匹配。
- 性能优化 :预编译
Regex、避免灾难性回溯、设置超时时间(适用于处理不可信输入)。
总结
| 方法 | 用途 | 返回值 |
|---|---|---|
Regex.IsMatch() |
判断是否匹配 | bool |
Regex.Match() |
获取第一个匹配 | Match |
Regex.Matches() |
获取全部匹配 | MatchCollection |
Regex.Replace() |
替换内容 | string |
Regex.Split() |
按规则分割 | string[] |
Regex.Escape() |
转义特殊字符 | string |
Regex.Unescape() |
取消转义 | string |
熟练掌握正则表达式后,在 C# 中处理文本、日志、配置文件、表单验证、数据清洗和批量替换等场景都会更加高效