正则表达式简单编程语句

认识正则表达式的类: Regex、Match、Group、Capture、RegexOptions、 MatchCollection、GroupCollection、CaptureCollection;
Regex:代表一个不可变的正则表达式;
Match:代表了regex类的实例的一次匹配结果;
MatchCollection:代表了Regex类的实例的所有匹配结
Group:表示单个捕获组的结果;
GroupCollection:表示单个匹配中的多个捕获组的集合;
Capture: 表示单个捕获中的一个子字符串;
CaptureCollection: 表示按照从里到外、从左到右的顺序由捕获组匹配到的所有子字符串集合
1.检查是否含有’他妈的’敏感词
static void Main(string[] args)
{
string conter = “正则表达式他妈的多么强大啊!”;
Regex regex = new Regex(“他妈的”);
if (regex.IsMatch(conter))
{
Console.WriteLine(“字符串 中包含有敏感词:他妈的!”);
}
Console.ReadLine();
}
2. 利用正则表达式进行替换
例一: static void Main(string[] args)
{
string conter = “正则表达式他妈的多么强大啊!”;
Regex regex = new Regex(“他妈的”);
string result = regex.Replace(conter, “是”);
Console.WriteLine(“替换后的字符串:” + result);
Console.ReadLine();
替换后结果:正则表达式是多么强大啊!
}
例二:还可以利用html标签包含起来
MatchEvaluator: 委托中调用的方法,可以对匹配结果进行处理
static void Main(string[] args)
{
string conter = “广东省高州市的荔枝and龙眼真多啊!”;
Regex regex = new Regex("\w{3}");
string result = regex.Replace(conter, new MatchEvaluator(Replace));
Console.WriteLine(“替换后的字符串:” + result);
Console.ReadLine();
替换后结果:

广东省

高州市

的荔枝

and

龙眼真

多啊!
}
private static string Replace(Match match)
{
return “

”+ match.Value +"

";
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值