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[] ❌ 否 ✅ 是 按匹配规则拆分字符串

相关推荐
Main. 2423 分钟前
从0到1学习Qt -- 常见控件之显示类控件
qt·学习
e***193525 分钟前
爬虫学习 01 Web Scraper的使用
前端·爬虫·学习
二川bro5 小时前
多模态AI开发:Python实现跨模态学习
人工智能·python·学习
石像鬼₧魂石5 小时前
Netcat,网络瑞士军刀(新手学习备用)
学习
todoitbo6 小时前
基于 DevUI MateChat 搭建前端编程学习智能助手:从痛点到解决方案
前端·学习·ai·状态模式·devui·matechat
Ma0407138 小时前
【机器学习】监督学习、无监督学习、半监督学习、自监督学习、弱监督学习、强化学习
人工智能·学习·机器学习
小熊officer9 小时前
Nginx学习
运维·学习·nginx
秋邱9 小时前
价值升维!公益赋能 + 绿色技术 + 终身学习,构建可持续教育 AI 生态
网络·数据库·人工智能·redis·python·学习·docker
Three~stone9 小时前
Matlab2025b的安装教程(附安装包和密钥破解文件)
学习·mysql·持续部署
爱学习的大牛1239 小时前
如何系统学习网络渗透测试:从入门到精通的完整指南
网络·学习