【问题标题】:Regular Expression to Match Multiline Comments匹配多行注释的正则表达式
【发布时间】:2013-04-20 14:15:50
【问题描述】:

我一直在尝试使用正则表达式匹配 HTML 文件中的 cmets,并通过 C#.net (VS2010) 解决方案将它们完全删除。 这是 cmets 的样子,

/*This flexibility is not available with most other programming languages. E.g. in Java,
the position for \G is remembered by the Matcher object.
The Matcher is strictly associated with a single regular expression and a single subject
string.*/

我确实尝试过/\*.+\*/

str = File.ReadAllText("Test.html");<br />
str = Regex.Replace(str, "/\*.+\*/", "", RegexOptions.Singleline);<br />
File.WriteAllText("Test.html", str);

但他们不适合我。我在论坛中关注了一些答案,但仍然没有运气。

如果有任何帮助,我将不胜感激:)

谢谢...

【问题讨论】:

  • 您是否在 HTML 中搜索 c# cmets?因为那时您需要选择 /**/ 之间的所有内容?
  • 不,Izzy,它是 HTML 文件中的 cmets :)
  • 不要 html cmets 看起来像这样 ? :D
  • @RaheelHasan 这就是我感到困惑的原因:)
  • 其中一些是。我已经设法删除了它们,但留下了 /* ... */。

标签: c# regex comments


【解决方案1】:

您必须在字符串文字中添加额外的转义层:

str = Regex.Replace(str, "/\*.+\*/", "", RegexOptions.Singleline);

产生/*.+*/ 作为模式,因为\ 是c# 字符串文字的转义元字符。您需要使用以下变体之一指定它(@ 防止处理转义序列,\\ 应该是不言自明的......):

str = Regex.Replace(str, @"/\*.+\*/", "", RegexOptions.Singleline);

str = Regex.Replace(str, "/\\*.+\\*/", "", RegexOptions.Singleline);

【讨论】:

  • 谢谢 Collapsar :) 完美运行。再次感谢您解释这一切。
【解决方案2】:

要找到/*comments*/,试试这个正则表达式:

/\/\*.+?\*\//ims

【讨论】:

  • 它在 VS 中返回一个错误:无法识别的转义序列顺便说一句谢谢 Raheel :)
  • 欢迎 :D 你试过@ 来防止自己处理转义序列吗?..
  • 哦...尝试使用 @ 但仍将 cmets 留在文件 mate 中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-26
  • 2012-10-12
  • 2021-09-03
  • 2011-10-29
  • 2010-11-14
  • 1970-01-01
相关资源
最近更新 更多