正则表达式删除包含特定单词的Java注释块

时间:2011-03-25 14:00:25

标签: regex replace javadoc

我正在尝试删除包含特定Java文档评论的评论

EG。我想删除此评论栏

/**
 * @author: Bob
 * @since 28.mar.2008
 *
 */

但不是这个块

/** 
 * This class represents ...
 *
 * and so on 
 */

到目前为止,我有这个正则表达式:

^/\*\*(.|\s)+?\*/

哪个匹配阻止评论

但我需要在那里的某些条件(例如包含“@since”的块注释) 我想关键是要使用前瞻,但我的正则表达目前并不是那么好。

任何可以帮助我改进的人

提前致谢 鲍勃

2 个答案:

答案 0 :(得分:8)

由于Java注释无法嵌套(感谢@Paŭlo),因此有一个正则表达式。

你可以用:

^/\*\*(?=(?:(?!\*/)[\s\S])*?@author: Bob)(?:(?!\*/)[\s\S])*\*/

说明如下:

^               # start-of-string
/\*\*           # literal "/**" (start-of-comment)

(?=             # begin positive look-ahead (...followed by)
  (?:           #   begin non-capturing group
    (?!         #     begin negative look-ahead (...not followed by)
      \*/       #       literal "*/"
    )           #     end negative look-ahead
    [\s\S]      #     anything, including newlines
  )*?           #   end group, repeat non-greedily
  @author: Bob  #   literal "@author: Bob"
)               # end positive look-ahead

                # ... now we have made sure there is "@author: Bob"
                #     before the end of the comment

(?:             # begin non-capturing group
  (?!           #   begin negative look-ahead
    \*/         #     literal "*/"
  )             #   end negative look-ahead
  [\s\S]        #   anything, including newlines (this eats the comment)
)*              # end group, repeat

\*/             # literal "*/" (end-of-comment)

答案 1 :(得分:0)

难道你不能简单地按@author关闭对@sincejavadoc的解释吗?

-nosince选项可以避免打印@since块,默认情况下不包含@author(需要-author选项)。

当然,如果您想混淆自己没有自己编写源代码,请将其从源代码中删除。 (但请确保这是在您获得的代码的许可范围内。)