简体   繁体   English

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

[英]regex replace with optional whitespaces

Suppose I have special tokens like [DOT], [COMMA] and similar. 假设我有[DOT],[COMMA]之类的特殊标记。 These can occur somewhere in a string. 这些可以出现在字符串中的某处。 Would it be possible to construct some regexp so it would replace them with an empty string and one of surrounding white spaces should be destroyed? 是否可以构造一些正则表达式,以便将其替换为空字符串,并销毁周围的空白之一? For example, "Mr[DOT] Drubber took his 12 [DONG] with him" should become "Mr Drubber took his 12 with him". 例如,“ [DOT] Drubber先生带走了他的12 [DONG]”应该变成“ Drubber先生带走了他的12 [DONG]”。 So this code doesn't work: 因此此代码不起作用:

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"

Or it's not possible to construct such a regex replcace? 还是不可能构造这样的正则表达式? Thank you for consideration. 谢谢你的考虑。

这个?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM