如何用括号替换 c# 中的特定单词? [英] How can I replace specific word in c# with parenthesis?
本文介绍了如何用括号替换 c# 中的特定单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下字符串:
string s = "The man is (old).";
如果我使用:
Regex.Replace(s,@"\b\(old\)\b", @"<b>$&</b>");
输出为:
那个男人(老).
但我会像这样改变整个(旧)词:
这个男人(老).
我该怎么做?
推荐答案
\b
不会匹配,因为 (
和 )
不是字字符.是否有理由将它们放在那里,因为您可以将它们排除在外:
\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>");
根据规范:
\b
:匹配必须出现在 \w(字母数字)和 \W(非字母数字)字符之间的边界上.
\b
: The match must occur on a boundary between a \w (alphanumeric) and a \W (nonalphanumeric) character.
-space-
和 )
都是非字母数字.(
和 .
相同,所以 \b
在这两种情况下都不会匹配.
-space-
and )
are both nonalphanumeric. The same for (
and .
, so \b
won't match in both cases.
这篇关于如何用括号替换 c# 中的特定单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文