【问题标题】:How to filter out c-type comments with regex? [duplicate]如何使用正则表达式过滤掉 c 类型的注释? [复制]
【发布时间】:2019-11-07 23:00:11
【问题描述】:

我试图过滤掉一行中的“c-style” cmets,所以我只剩下单词(或实际代码)。

这是我目前所拥有的:demo

正则表达式:

\/\*[^\/]*[^\*]*\*\/

文本:

/* 1111 */ one /*2222*/two /*3333 */ three/* 4444*/ four /*/**/ five /**/

【问题讨论】:

    标签: regex vb.net regex-group regex-greedy


    【解决方案1】:

    我的猜测是这个表达式可能会起作用,

    \/\*(\/\*\*\/)?\s*([^\/*]+?)\s*(?:\/?\*?\*?\/|\*)
    

    如果我们有不同的输入,我们会修改左右边界。

    在这个demo 中,解释了表达式,如果您可能感兴趣的话。

    【讨论】:

      【解决方案2】:

      我们可以尝试对以下模式进行正则表达式替换:

      /\*.*?\*/
      

      这匹配任何老式 C 风格的注释。它通过使用 lazy.*? 来匹配单个评论中的内容,在该评论结束之前。然后我们可以用空字符串替换,以有效地从输入中删除这些 cmets。

      代码:

      Dim input As String = "/* 1111 */ one /*2222*/two /*3333 */ three/* 4444*/ four /*/**/ five /**/"
      Dim output As String = Regex.Replace(input, "/\*.*?\*/", "")
      Console.WriteLine(input)
      Console.WriteLine(output)
      

      打印出来:

      one two  three four  five
      

      【讨论】:

      • 完美!所以这就是与“?”的交易。我不太确定如何使用它。谢谢。
      猜你喜欢
      • 2020-02-02
      • 2012-11-03
      • 2018-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-11
      • 2010-12-18
      相关资源
      最近更新 更多