我想用空格替换所有出现的"/* anytext here */"
(anytext here
可能是不同类型的文本。)我要做的是用空格替换所有注释。
我创建了一个正则表达式:
Regex regex = new Regex(@"/\*.*\*/");
...但它没有考虑多个/* ... */
模式的存在。例如,这个字符串:
"she /*sells*/ sea shells /*by the*/ sea shore"
...变为:
"she sea shore"
......而我想要的是:
"she sea shells sea shore"
有人可以帮助使用正确的正则表达式吗?
答案 0 :(得分:10)
使用 lazy 量词(.*?
)而不是贪心量词(.*
)。顺便说一句,您的文字*
字符需要使用\*
转义:
Regex regex = new Regex(@"/\*.*?\*/");
懒惰量词尝试尽可能少地匹配 (=到第一个*/
),而贪心量词尽可能匹配 (=到最后*/
)。有关详细信息,请访问以下MSDN页面: