【问题标题】:C# Regex.Replace with existing wordC# 正则表达式。用现有单词替换
【发布时间】:2015-06-03 14:20:02
【问题描述】:

我正在尝试使用正在工作的 Regex.Replace 突出显示文本字符串中的文本,但是当我搜索“问题”一词时,我希望“问题”也突出显示而不是“s”。它现在突出显示,但将“问题”替换为“问题”。我怎么知道当前比赛的结尾是否有“s”? 这就是我正在使用的

e.Row.Cells[6].Text = Regex.Replace(
    e.Row.Cells[6].Text, 
    "\\b" + Session["filterWord"].ToString() + "[s]{0,1}\\b", 
    "<b><font color=\"red\">" + Session["filterWord"].ToString() + "</font></b>", 
    RegexOptions.IgnoreCase);

【问题讨论】:

    标签: c# regex


    【解决方案1】:

    使用以下(捕获组):

    e.Row.Cells[6].Text = Regex.Replace(
        e.Row.Cells[6].Text, 
        "\\b" + Session["filterWord"].ToString() + "([s]?)\\b", 
        "<b><font color=\"red\">" + Session["filterWord"].ToString() + "$1</font></b>", 
        RegexOptions.IgnoreCase);
    

    【讨论】:

    • 更改搜索字符串以捕获更多内容,即 "\\b(" + Session["filterWord"].ToString() + "[s]?)\\b" 和替换为 "&lt;b&gt;&lt;font color=\"red\"&gt;$1&lt;/font&gt;&lt;/b&gt;" 也应该可以工作。
    猜你喜欢
    • 1970-01-01
    • 2015-07-16
    • 2015-09-03
    • 1970-01-01
    • 2022-12-10
    • 2020-01-06
    • 2021-08-05
    • 2010-09-27
    • 1970-01-01
    相关资源
    最近更新 更多