1

Consider the following string:

string s = "The man is (old).";

If I use:

Regex.Replace(s,@"\b\(old\)\b", @"<b>$&</b>");

The output is :
The man is (old).
But I would change the whole of the (old) word like this:
The man is (old).

How can I do this?

Philippe Leybaert
  • 168,566
  • 31
  • 210
  • 223
Houshang.Karami
  • 291
  • 1
  • 3
  • 11

2 Answers2

7

\b won't match because ( and ) are not word characters. Is there a reason why you put them there, because you could just leave them out:

 string replaced = Regex.Replace(s,@"\(old\)", @"<b>$&</b>");

According to the specs:

\b : The match must occur on a boundary between a \w (alphanumeric) and a \W (nonalphanumeric) character.

-space- and ) are both nonalphanumeric. The same for ( and ., so \b won't match in both cases.

Philippe Leybaert
  • 168,566
  • 31
  • 210
  • 223
1

You might not even need a regex... try

string result = s.Replace("(old)", "<b>(old)</b>");

or

string result = s.Replace("(", "<b>(").Replace(")", ")</b>");
Stephen Hewlett
  • 2,415
  • 1
  • 18
  • 31