How can I replace specific word in c# with parenthesis?

时光总嘲笑我的痴心妄想 提交于 2020-01-05 12:14:12

问题


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?


回答1:


\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.




回答2:


You might not even need a regex... try

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

or

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


来源:https://stackoverflow.com/questions/11439039/how-can-i-replace-specific-word-in-c-sharp-with-parenthesis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!