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

后端 未结 4 556
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  萌比男神i
    2020-12-20 01:40

    In complement of @Thai answer which I found very good, I would like to add a bit more:

    In this example using original regex only the last character of quotes will be matched: https://regex101.com/r/CoxFvJ/2

    So I modified a bit to allow capture of full quotes content and give a more talkative and generic example of content: https://regex101.com/r/CoxFvJ/3

    So final regex:

    /"((?:\\"|[^"])*)"|'((?:\\'|[^'])*)'|(\/\/.*|\/\*[\s\S]*?\*\/)/g

    Big thanks to Thai for unlocking me.

提交回复
热议问题