Search code examples
regexgroovycommentsmultilinereplaceall

Groovy remove multiline comment


How do I remove a multiline comment using groovy?

/* Use groovy replaceAll regex to 
   remove this comment */

I read-in the above text from a file, to a file object, and then I convert it into a string. And if the comment spans a single line, I can remove it using the replaceAll method as posted below:

def file = new File('myfile')
def fileString = file.getText()

println fileString.replaceAll('/\\* .* \\*/','')

I have tried to use the (?m) flag, but I can't get it to recognize my pattern. I have tried the following statements and they all fail to match my pattern.

fileString.replaceAll('(?m)/\\* (.*) \\*/'    ,'')  #multiline switch
fileString.replaceAll('(/\\*)(.|\n\r)*(\\*/)' ,'')  #match all .* (include \n\r)

I thought about using the DotAll, the (\s) at the end, and ${}. But, I am not sure how to effectively mix it into the regular expression. Any help would be welcomed. Thanks.


Solution

  • Try this expression:

    '(?s)/\\*.*?\\*/'
    

    (?m) doesn't make . match new lines, (?s) does that.