C#学习13——正则表达式

一、正则表达式

一种匹配输入文本的模式,是由特殊字符组成,用于匹配字符串中的字符组合。

二、正则表达式有哪些?

1.Regex 类(引入System.Text.RegularExpressions;)

Regex 类用于表示一个正则表达式。

1)Regex.Match(inputString, "pattern");

返回第一个匹配项(即只找第一个)。

cs 复制代码
string input = "123abc456";
Match match = Regex.Match(input, @"\d+");

if (match.Success)
{
    Console.WriteLine(match.Value); // 输出: 123
}
2)Regex.Matches(...)

返回所有匹配项(全部找到)。

cs 复制代码
string input = "123abc456def789";
MatchCollection matches = Regex.Matches(input, @"\d+");

foreach (Match match in matches)
{
    Console.WriteLine(match.Value); // 输出: 123, 456, 789
}
3)Regex.IsMatch(...)

当你不需要具体匹配内容,只要知道是否"存在匹配"即可。

cs 复制代码
string input = "abc123xyz";
bool hasDigits = Regex.IsMatch(input, @"\d+");

Console.WriteLine(hasDigits); // 输出: True
4)Regex.Replace(...)

替换匹配到的内容为指定字符串。

eg1:

替换所有数字 Regex.Replace(text, @"\d+", "*")

eg2:

cs 复制代码
string input = "电话:123-456-7890,邮箱:test@example.com";

// 替换所有数字为 *
string result1 = Regex.Replace(input, @"\d", "*");
Console.WriteLine(result1);
// 输出:电话:***-***-****,邮箱:test@example.com

// 替换所有邮箱地址为 [隐藏]
string result2 = Regex.Replace(input, @"\b[\w.-]+@[\w.-]+\.\w+\b", "[隐藏]");
Console.WriteLine(result2);
// 输出:电话:123-456-7890,邮箱:[隐藏]
5)Regex.Split(...)

根据正则表达式匹配内容,将字符串分割成多个部分。

cs 复制代码
string input = "apple, banana; orange|grape";

// 按照非单词字符(逗号、分号、竖线)进行分割
string[] parts = Regex.Split(input, @"[,\s;|]+");

foreach (string part in parts)
{
    Console.WriteLine(part);
}
// 输出:
// apple
// banana
// orange
// grape

6.区别:

方法 返回类型 是否返回匹配内容 是否修改原字符串 主要用途

Match(...) Match ✅ 是(第一个) ❌ 否 获取第一个匹配项

Matches(...) MatchCollection ✅ 是(全部) ❌ 否 获取所有匹配项

IsMatch(...) bool ❌ 否 ❌ 否 判断是否匹配成功

Replace(...) string ❌ 否 ✅ 是 替换匹配内容

Split(...) string[] ❌ 否 ✅ 是 按匹配规则拆分字符串

相关推荐
驱动探索者25 分钟前
linux mailbox 学习
linux·学习·算法
进阶小白猿31 分钟前
Java技术八股学习Day33
java·开发语言·学习
收菜福星32 分钟前
当AI Agent成为大学标配:2026年学习模式的深层变革
人工智能·学习
蒟蒻的贤43 分钟前
yolo12结构学习
学习
●VON2 小时前
CANN推理引擎:从云端到边缘的极致加速与部署实战
学习·react native
笔画人生2 小时前
深度解析 CANN 项目:以 `ops-transformer` 为例探索高性能 AI 算子库
学习·开源
AI视觉网奇2 小时前
3d数字人 ue blender 绑定衣服对齐 2026
学习·ue5
Nan_Shu_6142 小时前
学习: Blender 基础篇
学习·blender
奶茶精Gaaa3 小时前
工具分享--json在线转换工具
学习
wdfk_prog3 小时前
[Linux]学习笔记系列 -- [drivers][I2C]I2C
linux·笔记·学习