C# 正则表达式完全指南:Regex 类、常用模式与实战示例
正则表达式是可匹配输入文本的模式。.NET 框架提供正则表达式引擎执行匹配。模式由字符字面量、运算符、构造组成。
正则表达式构造分类
- 字符转义
- 字符类
- 锚点
- 分组构造
- 量词
- 反向引用构造
- 替代构造
- 替换
- 杂项构造
Regex 类常用方法
| 序号 | 方法及说明 |
|---|---|
| 1 | IsMatch(input):指示正则是否在输入字符串中找到匹配 |
| 2 | IsMatch(input, startat):从指定位置开始匹配 |
| 3 | IsMatch(input, pattern):静态方法,指定模式匹配 |
| 4 | Matches(input):搜索所有匹配项,返回 MatchCollection |
| 5 | Replace(input, replacement):替换所有匹配项 |
| 6 | Split(input):按正则模式拆分字符串数组 |
实战示例
示例 1:匹配以 'S' 开头的单词
using System;
using System.Text.RegularExpressions;
namespace RegExApplication {
class Program {
private static void showMatch(string text, string expr) {
Console.WriteLine("The Expression: " + expr);
MatchCollection mc = Regex.Matches(text, expr);
foreach (Match m in mc) Console.WriteLine(m);
}
static void Main(string[] args) {
string str = "A Thousand Splendid Suns";
Console.WriteLine("Matching words that start with 'S': ");
showMatch(str, @"\bS\S*");
Console.ReadKey();
}
}
}
输出:
Matching words that start with 'S':
The Expression: \bS\S*
Splendid
Suns
示例 2:匹配以 'm' 开头 'e' 结尾的单词
string str = "make maze and manage to measure it";
showMatch(str, @"\bm\S*e\b");
输出:
Matching words start with 'm' and ends with 'e':
The Expression: \bm\S*e\b
make
maze
manage
measure
示例 3:替换多余空白字符
using System;
using System.Text.RegularExpressions;
namespace RegExApplication {
class Program {
static void Main(string[] args) {
string input = "Hello World ";
string pattern = @"\s+";
string replacement = " ";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
Console.WriteLine("Original String: {0}", input); // Hello World
Console.WriteLine("Replacement String: {0}", result); // Hello World
Console.ReadKey();
}
}
}
常用正则模式速查
| 模式 | 说明 | 示例匹配 |
|---|---|---|
\d | 数字 | 0-9 |
\D | 非数字 | a, # |
\w | 单词字符 | a, Z, 0, _ |
\W | 非单词字符 | @, 空格 |
\s | 空白字符 | 空格, \t, \n |
\S | 非空白字符 | a, 1 |
. | 任意字符(除换行) | a, 1, @ |
^ | 字符串开始 | |
$ | 字符串结束 | |
\b | 单词边界 | |
* | 0 次或多次 | |
+ | 1 次或多次 | |
? | 0 次或 1 次 | |
{n} | 恰好 n 次 | |
{n,} | 至少 n 次 | |
{n,m} | n 到 m 次 | |
(...) | 捕获组 | |
(?:...) | 非捕获组 | |
| | 或 |
常用验证正则
- 邮箱:
^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$ - 手机号(中国):
^1[3-9]\d{9}$ - 身份证:
^\d{17}[\dXx]$ - URL:
^https?://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$ - IPv4:
^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$
性能与最佳实践
- 复用
Regex实例或使用静态方法避免重复编译 - 使用
RegexOptions.Compiled提高重复执行性能(首次编译较慢) - 避免灾难性回溯:慎用嵌套量词
(a+)+,优先用占有量词或原子组 - 设置
Regex.MatchTimeout防止恶意输入导致拒绝服务 - 大量替换用
StringBuilder+Regex.Replace回调
C语言
- C# 表达式、语句与代码块:全面指南与实战示例
- 掌握 C# 字符串:基础、操作与进阶技巧完全指南
- C++ 字符串函数实战:strcpy、strcat、strlen、strcmp 详解与示例
- C 语言字符串完全指南:声明、输入输出与库函数详解
- Python str.count() 完全指南:统计字符与子串出现次数实战
- 理解 Java 表达式、语句与代码块
- 精通 Java 字符串:创建、方法与最佳实践
- 精通 Java 枚举字符串表示:默认行为、toString 重写与进阶模式
- 掌握 Java Lambda 表达式:从基础到 Stream API 实战
- Java Strings 类:掌握字符串创建与操作
- Java 正则表达式完全指南:掌握 java.util.regex 模式匹配
- Java 8 概览:函数式编程、流式 API 与日期时间新特性