2

我想"/* anytext here */"用空格替换所有出现的 (anytext here可能是不同类型的文本。)我想要做的是用空格替换所有评论。

我创建了一个正则表达式:

Regex regex = new Regex(@"/\*.*\*/");

...但它不考虑多种/* ... */模式的存在。例如,这个字符串:

"she /*sells*/ sea shells /*by the*/ sea shore" 

...变成:

"she   sea shore" 

...而我想要的是:

"she   sea shells   sea shore"

有人可以帮助正确的正则表达式吗?

4

1 回答 1

10

使用惰性量词 ( .*?) 而不是贪心量词( .*)。顺便说一句,您的文字*字符需要转义\*

Regex regex = new Regex(@"/\*.*?\*/");

惰性量词尝试尽可能少地匹配(= 到 first */),而贪婪量词尽可能多地匹配(= 到 last */)。更多详细信息可以在以下 MSDN 页面中找到:

于 2012-08-07T20:05:45.057 回答