【问题标题】:Find & replace text while maintaining the text CaSe of match [duplicate]查找和替换文本,同时保持匹配的文本 CaSe [重复]
【发布时间】:2019-10-01 14:06:09
【问题描述】:

我在一个网站上有一个简单的功能,用户输入要搜索的关键字,匹配的关键字用<span></span>包装,匹配的关键字的颜色也会改变。

下面的代码查找并替换标题中找到匹配项的关键字,但更改匹配项的大小写会根据关键字的输入方式进行更改。

protected String getTitle(object title)
{
    string sTitle = title.ToString();

    Regex regex = null;
    string pattern = @"(\b(?:" + _Keyword.ToString().Trim() + @")\b)(?![^<]*?>)";
    regex = new Regex(pattern,RegexOptions.IgnoreCase);
    sTitle = regex.Replace(sTitle, "<span class='keyword-highlight'>" + _Keyword + "</span>");
    return sTitle;
}

实际文本 = Trump asked Australia to help investigate Mueller 搜索关键字 = australia

假设我输入了小写的关键字australia,在这种情况下,它会找到匹配项并将其替换为Australiaaustralia,这在语法上是错误的,因为我想将文本大小写保持原样实际的句子。

结果 = Trump asked australia to help investigate Mueller

如何在上述代码中进行此更改,如果我删除 RegexOptions.IgnoreCase 那么它将不匹配,因为现在搜索关键字是 CaSe SenSiTive

【问题讨论】:

  • 答案是here。您不需要捕获组,因为您想用一对标签包装 整个匹配,因为存在 &amp;$ 反向引用。

标签: c# regex


【解决方案1】:

只需使用$1(第一个捕获的组)

Substituting a Numbered Group

$number 语言元素包含与 替换字符串中的数字捕获组,其中数字是 捕获组的索引。

示例

var input = "Trump asked Australia to help investigate Mueller";
var keyword = "australia"; 

var pattern = @"(\b(?:" + keyword.Trim() + @")\b)(?![^<]*?>)";
var result = Regex.Replace(input, pattern, "<span class='keyword-highlight'>$1</span>", RegexOptions.IgnoreCase);

Console.WriteLine(result);

输出

Trump asked <span class='keyword-highlight'>Australia</span> to help investigate Mueller

【讨论】:

  • 哦,这很简单,我学到了新东西..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-21
  • 2023-02-01
  • 2016-08-04
  • 1970-01-01
  • 2018-09-07
  • 2012-08-29
  • 2016-09-22
相关资源
最近更新 更多