# 定义

正则表达式是一种用于匹配字符串的模式。它可以用来查找、验证、替换和分割字符串。正则表达式由一系列字符和特殊符号组成,这些符号定义了匹配规则

# 创建

在 C# 中,正则表达式的主要类和方法位于 System.Text.RegularExpressions 命名空间中

常用的类包括 RegexMatchGroupCapture

string str = "There are 123 apples and 456 oranges.";
// 创建正则表达式对象
Regex regex = new Regex(@"\d+"); // 匹配一个或多个数字
// 查找匹配项
MatchCollection matches = regex.Matches(str);
// 输出匹配结果
foreach (Match match in matches)
{
    Console.WriteLine($"Found match: {match.Value}");
}

# 常用方法

# IsMatch

检查字符串是否包含匹配项

string str = "There are 123 apples and 456 oranges.";
Regex regex = new Regex(@"\d+");
bool hasMatch = regex.IsMatch(str);
Console.WriteLine(hasMatch); // True

# Match

查找第一个匹配项

string str = "There are 123 apples and 456 oranges.";
Regex regex = new Regex(@"\d+");
Match match = regex.Match(str);
if (match.Success) {
    Console.WriteLine("匹配到的值:" + match.Value); // 匹配到的值:123
}
else {
    Console.WriteLine("未匹配到!");
}

# Matches

查找所有匹配项

string str = "There are 123 apples and 456 oranges.";
Regex regex = new Regex(@"\d+");
MatchCollection matches = regex.Matches(str);
foreach (Match item in matches) {
    Console.WriteLine(item);
}
// 输出
123
456

# Replace

替换匹配项

string str = "There are 123 apples and 456 oranges.";
Regex regex = new Regex(@"\d+");
string result = regex.Replace(str, "XXX");
Console.WriteLine("替换后:" + result); // 替换后:There are XXX apples and XXX oranges.

# Split

分割字符串

string str = "There are 123 apples and 456 oranges.";
Regex regex = new Regex(@"\d+");
string[] parts = regex.Split(str);
foreach (string item in parts) {
    Console.WriteLine(item);
}
// 输出
There are
 apples and
 oranges.

# 常见匹配语句

// 匹配数字
Regex regex = new Regex(@"\d+");
// 匹配电子邮件地址
Regex regex = new Regex(@"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z]{2,}\b");
// 匹配 URL
Regex regex = new Regex(@"https?://[^\s]+");
// 匹配电话号码
Regex regex = new Regex(@"\b\d{3}[-.\s]?\d{3}[-.\s]?\d{4}\b");