Regex Error: Nothing to Repeat

前端 未结 3 883
北海茫月
北海茫月 2021-01-26 08:50

I\'m new to regular expressions in JavaScript, and I cannot get a regex to work. The error is:

Uncaught SyntaxError: Invalid regular expression: /(.

3条回答
  •  鱼传尺愫
    2021-01-26 09:38

    You can emulate a possessive quantifier with javascript (since you can emulate an atomic group that is the same thing):

    a++ => (?>a+) => (?=(a+))\1
    

    The trick use the fact that the content of a lookahead assertion (?=...) becomes atomic once the closing parenthesis reached by the regex engine. If you put a capturing group inside (with what you want to be atomic or possessive), you only need to add a backreference \1 to the capture group after.

    About your pattern:

    .*+x is an always false assertion (like .*+=): since .* is greedy, it will match all possible characters, if you make it possessive .*+, the regex engine can not backtrack to match the "x" after.

    What you can do:

    Instead of using the vague .*, I suggest to describe more explicitly what can contain each capture group. I don't think you need possessive quantifiers for this task.

    Trying to split the string on operator can be a good idea too, and avoids to build too complex patterns.

提交回复
热议问题