Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

javascript - Regex Error: Nothing to Repeat

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

Uncaught SyntaxError: Invalid regular expression: /(.*+x.*+)=(.++)/: Nothing to repeat

I know there are many questions like this other than this, but I cannot get this to work based on other people's answers and suggestions.

The regex is:

/(.*+x.*+)=(.++)/

and it is used to match simple equations with the variable x on one side.

Some examples of the expressions it's supposed to match are (I'm writing a simple program to solve for the variable x):

  • 240x=70

  • x+70=23

  • 520/x=2

  • 13989203890189038902890389018930.23123213281903890128390x+23123/2=3

  • etc.

I'm trying out possessive quantifiers (*+) because before, the expressions were greedy and crashed my browser, but now this error that I haven't encountered has come up.

I'm sure it doesn't have to do with escaping, which was the problem for many other people.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...