javascript regex of a javascript string

后端 未结 4 1618
迷失自我
迷失自我 2020-12-04 04:14

I need to match a javascript string, with a regular expression, that is a string enclosed by single quote and can only contain a backslashed single quote.

The exampl

4条回答
  •  爱一瞬间的悲伤
    2020-12-04 04:33

    Try this one:

    /'(?:[^'\\]|\\'|\\(?!'))*'/
    

    Test it in your console:

    /'(?:[^'\\]|\\'|\\(?!'))*'/.exec("'abc\\\'de\\\'fg'")
    

    It'll match

    • Any number of characters that are:
      • NOT ' or \ (except)
      • \' (or)
      • \ (not followed by ')

    If you want it to match the entire string, use the ^ start-of-string and $ end-of-string markers:

    /^'(?:[^'\\]|\\'|\\(?!'))*'$/
    

    ... which will match 'string', 'string\'s are awesome' but not 'string's are awesome' or 'string's

提交回复
热议问题