Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Regex.Replace with existing word

Tags:

c#

regex

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);
like image 917
user2809051 Avatar asked Nov 19 '25 22:11

user2809051


1 Answers

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);
like image 139
karthik manchala Avatar answered Nov 22 '25 12:11

karthik manchala



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!