match “//” comments with regex but not inside a quote

后端 未结 4 564
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-20 01:33

I need to match and replace some comments. for example:

$test = \"the url is http://www.google.com\";// comment \"<-- that quote needs to be matched
         


        
4条回答
  •  无人及你
    2020-12-20 02:03

    I have to admit, this regex took me a while to generate...but I'm pretty sure this will do what you are looking for:

    
    

    Here's what's going on in the regex:

    ^ # start with the beginning of the line
    (?:           # don't capture the following
     (
      ([^"'\/]*   # start the line with any character as long as it isn't a string or a comment
       (
        ("[^"]*") # grab a double quoted string
        |         # OR 
        ('[^']*') # grab a single quoted string
       )?         # but...we don't HAVE to match a string
       [\s]*      # allow for any amount of whitespace
      )?          # but...we don't HAVE to have any characters before the comment begins
      \/\/        # match the start of a comment
      [^"]*       # match any number of characters that isn't a double quote
     )            # end un-caught grouping
    )             # end the non-capturing declaration
    "             # match your commented double quote
    

    The while loop in javascript is just find/replacing until it can't find any additional matches in a given line.

提交回复
热议问题