How to match string in single or double quoted using regex

前端 未结 3 1269
一生所求
一生所求 2021-01-18 16:48

I\'m trying to write a regex that matches strings as the following:

translate(\"some text here\")

and

translate(\'some text here\'

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-18 17:23

    @translate\(
    ([\'"])      # capture quote char
    ((?:
      (?!\1).    # not a quote
    |            # or
      \\\1       # escaped one
    )* # 
    [^\\\\]?)\1    # match unescaped last quote char
    \)@gx
    

    Fiddle:

    ok: translate("some text here")
    ok: translate('some text here')
    ok: translate('"some text here..."')
    ok: translate("a\"b\"c\"d")
    ok: translate("")
    no: translate("a\"b"c\"d")
    

提交回复
热议问题