正则表达式替换为可选的空格

时间:2011-11-14 18:44:15

标签: .net regex

假设我有像[DOT],[COMMA]等类似的特殊令牌。这些可以发生在字符串中的某个地方。 是否可以构造一些正则表达式,以便用空字符串替换它们,并且应该销毁周围的一个空格?例如, “先生[DOT] Drubber带着他的12 [DONG]”应该成为“Drubber先生带他12岁”。 所以这段代码不起作用:

string strToFix = "Mr[DOT] Drubber took his 12 [DONG] with him";
string templateWords = GetSpecialTokens(); // \[DOT\]|\[COMMA\] etc
string wrongString = Regex.Replace(strToFix, templateWords, "");
//wrongString becomes "Mr Drubber took his 12  with him"

或者不可能构建这样的正则表达式复制品? 谢谢你的考虑。

1 个答案:

答案 0 :(得分:0)

此?

resultString = Regex.Replace(subjectString, @"\[(DOT|DONG)\]", "");