Regex to replace comments with number of new lines

Jong Lee :

I want to replace all Java-style comments (/* */) with the number of new lines for that comment. So far, I can only come up with something that replaces comments with an empty string

String.replaceAll("/\\*[\\s\\S]*?\\*/", "")

Is it possible to replace the matching regexes instead with the number of new lines it contains? If this is not possible with just regex matching, what's the best way for it to be done?

For example,

/* This comment
has 2 new lines
contained within */

will be replaced with a string of just 2 new lines.

user557597 :

Since Java supports the \G construct, just do it all in one go.
Use a global regex replace function.

Find

"/(?:\\/\\*(?=[\\S\\s]*?\\*\\/)|(?<!\\*\\/)(?!^)\\G)(?:(?!\\r?\\n|\\*\\/).)*((?:\\r?\\n)?)(?:\\*\\/)?/"

Replace

"$1"

https://regex101.com/r/l1VraO/1

Expanded

 (?:
      / \* 
      (?= [\S\s]*? \* / )
   |  
      (?<! \* / )
      (?! ^ )
      \G 
 )
 (?:
      (?! \r? \n | \* / )
      . 
 )*
 (                             # (1 start)
      (?: \r? \n )?
 )                             # (1 end)
 (?: \* / )?

==================================================
==================================================

IF you should ever care about comment block delimiters started within
quoted strings like this

String comment = "/* this is a comment*/"

Here is a regex (addition) that parses the quoted string as well as the comment.
Still done in a single regex all at once in a global find / replace.

Find

"/(\"[^\"\\\\]*(?:\\\\[\\S\\s][^\"\\\\]*)*\")|(?:\\/\\*(?=[\\S\\s]*?\\*\\/)|(?<!\")(?<!\\*\\/)(?!^)\\G)(?:(?!\\r?\\n|\\*\\/).)*((?:\\r?\\n)?)(?:\\*\\/)?/"

Replace

"$1$2"

https://regex101.com/r/tUwuAI/1

Expanded

    (                             # (1 start)
         "
         [^"\\]* 
         (?:
              \\ [\S\s] 
              [^"\\]* 

         )*
         "
    )                             # (1 end)
 |  
    (?:
         / \* 
         (?= [\S\s]*? \* / )
      |  
         (?<! " )
         (?<! \* / )
         (?! ^ )
         \G 
    )
    (?:
         (?! \r? \n | \* / )
         . 
    )*
    (                             # (2 start)
         (?: \r? \n )?
    )                             # (2 end)
    (?: \* / )?

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=140757&siteId=1