简体   繁体   中英

C# Regex.Replace with existing word

I am trying to highlight text in a string of text using Regex.Replace which is working, but when I search for the word "problem" I want "problems" to also highlight just not the "s". It highlights right now but replaces "problems" with "problem". How can I know if the current match has an "s" at the end? This is what I'm using

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

Use the following (capture groups):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM