/// 检查字符串中是否有“孙权”这个敏感词
/// </summary>
public void IsMatchDemo()
{
string source = "刘备ABC关羽ABc张飞Abc赵云abc诸葛亮aBC孙权abC周瑜AbC鲁肃aBc曹操许攸郭嘉需晃袁绍";
Regex regex = new Regex("孙权");
//if (Regex.IsMatch(source, "孙权"))
//下面这句和上面被注释掉的一句作用的同样的
if (regex.IsMatch(source))
{
Console.WriteLine("字符串中包含有敏感词:孙权!");
}
/// <summary>
/// 检查字符串中是否有“def”的任何大小写形式
/// </summary>
public void IsMatchDemoWithOption()
{
string source = "刘备ABC关羽ABc张飞Abc赵云abc诸葛亮aBC孙权abC周瑜AbC鲁肃aBc曹操DEF许攸郭嘉需晃袁绍";
Regex regex = new Regex("def",RegexOptions.IgnoreCase);
if (regex.IsMatch(source))
{
Console.WriteLine("字符串中包含有敏感词:def!");
}
}
//if (Regex.IsMatch(source, "孙权"))
//下面这句和上面被注释掉的一句作用的同样的
if (regex.IsMatch(source))
/// 实现字符串替换功能
/// </summary>
public void Replace()
{
string source = "刘备ABC关羽ABc张飞Abc赵云abc诸葛亮aBC孙权abC周瑜AbC鲁肃aBc曹操DEF许攸郭嘉需晃袁绍";
Regex regex = new Regex("abc", RegexOptions.IgnoreCase);
string result=regex.Replace(source, "|");
Console.WriteLine("原始字符串:" + source);
Console.WriteLine("替换后的字符串:" + result);
}
/// 实现字符串替换功能
/// </summary>
public void ReplaceMatchEvaluator()
{
string source = "刘备ABC关羽ABc张飞Abc赵云abc诸葛亮aBC孙权abC周瑜AbC鲁肃aBc曹操DEF许攸郭嘉需晃袁绍";
Regex regex = new Regex("[A-Z]{3}", RegexOptions.IgnoreCase);
string result = regex.Replace(source, new MatchEvaluator(OutPutMatch));
Console.WriteLine("原始字符串:" + source);
Console.WriteLine("替换后的字符串:" + result);
}
/// <summary>
/// MatchEvaluator委托中调用的方法,可以对匹配结果进行处理
/// </summary>
/// <param name="match">操作过程中的单个正则表达式匹配</param>
/// <returns></returns>
private string OutPutMatch(Match match)
{
return "<b>" + match.Value + "</b>";
}