Java - Regex - Remove comments

后端 未结 1 1711
感情败类
感情败类 2020-12-01 20:08

I want to remove comments in Java code. I have seen a lot of examples, but each was written wrong.

Here is example of code:

String somestring = \"htt         


        
相关标签:
1条回答
  • 2020-12-01 21:03

    Already commented this but lets see how far we get. Java doesn't do regex literals so stripping that one from this answer we get the following regex:

    ((['"])(?:(?!\2|\\).|\\.)*\2)|\/\/[^\n]*|\/\*(?:[^*]|\*(?!\/))*\*\/
    

    Regular expression visualization

    Debuggex Demo

    If we then "replace" every match with the first capture group, every match that doesn't have a capture group to begin with (i.e. a comment) is removed:

    Regex101 substitution Demo

    A explanation of the more generic "match this except in conditions a|b|c"-technique I employed is available here.

    0 讨论(0)
提交回复
热议问题