正则表达式(regular expression,简称 regex)是一种用于匹配、查找、替换字符串的规则。在 c# 中,正则表达式由 system.text.regularexpressions 命名空间提供。
掌握 regex 后,可以轻松完成:
- ✔ 验证手机号
- ✔ 验证邮箱
- ✔ 提取数字
- ✔ 查找指定字符串
- ✔ 批量替换文本
- ✔ 分割字符串
- ✔ 解析日志
- ✔ 数据清洗
一、命名空间
using system.text.regularexpressions;
二、regex 类
最常用的是 regex 类。
常见方法:
| 方法 | 作用 |
|---|---|
| ismatch() | 是否匹配 |
| match() | 获取第一个匹配 |
| matches() | 获取所有匹配 |
| replace() | 替换字符串 |
| split() | 分割字符串 |
| escape() | 转义特殊字符 |
| unescape() | 取消转义 |
三、最简单的例子
判断字符串中是否包含数字。
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()
用于判断是否符合规则。
语法:
regex.ismatch(字符串, 正则表达式)
例如:
string phone = "13812345678";
bool result = regex.ismatch(phone, @"^1\d{10}$");
console.writeline(result);输出
true
解释:
^
开始
1
第一位必须是1
\d
数字
{10}
后面10位
$
结束五、regex.match()
返回第一个匹配结果。
例如:
string str = "abc123xyz456"; match match = regex.match(str, @"\d+"); console.writeline(match.value);
输出
123
说明:
\d+
表示:
一个或多个数字。
match 常用属性
match.value
匹配内容
match.index
开始位置
match.length
长度
例如:
console.writeline(match.value); console.writeline(match.index); console.writeline(match.length);
输出:
123 3 3
六、regex.matches()
获取所有匹配。
例如:
string str = "abc123xyz456aaa789";
matchcollection mc = regex.matches(str, @"\d+");
foreach (match item in mc)
{
console.writeline(item.value);
}输出:
123 456 789
七、regex.replace()
替换。
例如:
把所有数字替换成 *
string str = "abc123xyz456"; string result = regex.replace(str, @"\d", "*"); console.writeline(result);
输出
abc***xyz***
替换整个数字
string result = regex.replace(str, @"\d+", "***");
输出
abc***xyz***
八、regex.split()
按规则切割。
例如:
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。
十一、分组 ()
例如:
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(匹配选项)
regex.ismatch(
"abc",
"abc",
regexoptions.ignorecase);常见选项:
| 选项 | 说明 |
|---|---|
| ignorecase | 忽略大小写 |
| multiline | 多行模式(^、$ 匹配每行) |
| singleline | 单行模式(. 可匹配换行) |
| compiled | 编译正则,提高重复使用性能(首次创建开销略高) |
| cultureinvariant | 与区域性无关的匹配 |
十四、逐字字符串(@)
建议写正则时使用:
@"\d+"
而不是
"\\d+"
这样无需对反斜杠进行二次转义,可读性更高。
十五、实战案例
1. 提取所有邮箱
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. 隐藏手机号中间四位
string phone = "13812345678";
string result = regex.replace(
phone,
@"(\d{3})\d{4}(\d{4})",
"$1****$2");
console.writeline(result);输出:
138****5678
3. 删除所有 html 标签
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# 中处理文本、日志、配置文件、表单验证、数据清洗和批量替换等场景都会更加高效
以上就是c#中正则表达式的使用方法详解的详细内容,更多关于c#正则表达式使用方法的资料请关注代码网其它相关文章!
发表评论