C#中Regex类用法
来源:互联网 发布:投资组合优化模型 编辑:程序博客网 时间:2024/05/27 02:33
使用Regex类需要引用命名空间:using System.Text.RegularExpressions;
利用Regex类实现验证
示例1:注释的代码所起的作用是相同的,不过一个是静态方法,一个是实例方法
var source = "刘备关羽张飞孙权";
//Regex regex = new Regex("孙权");
//if (regex.IsMatch(source))
//{
// Console.WriteLine("字符串中包含有敏感词:孙权!");
//}
if (Regex.IsMatch(source, "孙权"))
{
Console.WriteLine("字符串中包含有敏感词:孙权!");
}
Console.ReadLine();
示例2:使用带两个参数的构造函数,第二个参数指示忽略大小写,很常用
var source = "123abc345DEf";
Regex regex = new Regex("def",RegexOptions.IgnoreCase);
if (regex.IsMatch(source))
{
Console.WriteLine("字符串中包含有敏感词:def!");
}
Console.ReadLine();
使用Regex类进行替换
示例1:简单情况
var source = "123abc456ABC789";
// 静态方法
//var newSource=Regex.Replace(source,"abc","|",RegexOptions.IgnoreCase);
// 实例方法
Regex regex = new Regex("abc", RegexOptions.IgnoreCase);
var newSource = regex.Replace(source, "|");
Console.WriteLine("原字符串:"+source);
Console.WriteLine("替换后的字符串:" + newSource);
Console.ReadLine();
结果:
原字符串:123abc456ABC789
替换后的字符串:123|456|789
示例2:将匹配到的选项替换为html代码,我们使用了MatchEvaluator委托
var source = "123abc456ABCD789";
Regex regex = new Regex("[A-Z]{3}", RegexOptions.IgnoreCase);
var newSource = regex.Replace(source,new MatchEvaluator(OutPutMatch));
Console.WriteLine("原字符串:"+source);
Console.WriteLine("替换后的字符串:" + newSource);
Console.ReadLine();
private static string OutPutMatch(Match match)
{
return "<b>" +match.Value+ "</b>";
}
输出:
原字符串:123abc456ABCD789
替换后的字符串:123<b>abc</b>456<b>ABC</b>D789
- C#中Regex类用法
- C# Regex类用法
- C# Regex类用法
- C# Regex类用法
- C# Regex类用法
- C#正则表达式的Regex类用法
- C#正则表达式Regex类的用法
- C#正则表达式Regex类的用法
- C# Regex用法小结
- C#正则表达式编程(二):Regex类用法
- C#正则表达式编程(二):Regex类用法
- C#正则表达式的使用(Regex类用法)
- C#正则表达式编程(二):Regex类用法
- C#正则表达式编程(二):Regex类用法
- C#正则表达式之Regex类用法详解
- C# Regex 类
- C# Regex类详解
- C# Regex类详解
- C++11语言可用性的强化
- 自定义控件无法直接添加到axml解决方法
- redis的消息队列
- 28. Implement strStr()
- C#——多态
- C#中Regex类用法
- mysql命令
- Error(408) hv01.cloud.cn has an unsupported version of the Virtual Machine Manager agent installd
- cssText实现js添加样式
- redis删除指定开头的键值数据(命令行)
- 帝国cms制作手机wap站完美教程
- 注册码系统防破解教程,如何防破解?
- 入门深度学习mxnet框架——运行mnist手写数字例子
- jquery 遍历