正则表达式错误:没什么可重复的 [英] Regex Error: Nothing to Repeat
问题描述
我不熟悉JavaScript中的正则表达式,因此无法使用正则表达式.错误是:
I'm new to regular expressions in JavaScript, and I cannot get a regex to work. The error is:
未捕获到的SyntaxError:无效的正则表达式:
/(.* + x.* +)\ =(.++)/
:无需重复
我知道除此以外还有很多这样的问题,但是我无法根据其他人的回答和建议来使它起作用.
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.
正则表达式为:
/(.*+x.*+)\=(.++)/
,它用于在一侧将简单方程式与变量 x
匹配.
and it is used to match simple equations with the variable x
on one side.
一些应该匹配的表达式示例(我正在编写一个简单的程序来求解变量 x
):
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
等
我正在尝试所有格量词( * +
),因为以前,表达式很贪婪,导致浏览器崩溃,但是现在出现了我从未遇到的错误.
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.
推荐答案
您可以模拟所有量词与javascript(因为您可以模拟原子组一样)):
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.
关于您的图案:
.* + x
是一个总是错误的断言(例如.* + =
):由于.*
是贪婪的,因此它将匹配所有可能的字符,如果使它具有所有格.* +
,则正则表达式引擎无法回溯以匹配"x".
.*+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.
您可以做什么:
我建议不要使用含糊的.*
,而应更明确地描述可以包含每个捕获组的物质.我认为您不需要该任务的所有格修饰符.
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.
这篇关于正则表达式错误:没什么可重复的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!