C#Regex.Replace with existing word

时间:2015-06-03 14:20:02

标签: c# regex

我正在尝试使用正在运行的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);

1 个答案:

答案 0 :(得分:4)

使用以下(捕获组):

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);