JavaScript:正则表达式中的无效量词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3713290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript: Invalid quantifier in regex
提问by Stephen
The regex is constructed on the fly, but I've output it to firebug:
正则表达式是即时构建的,但我已将其输出到 firebug:
(.{1,38})(+|$\n?)
the error is
错误是
invalid quantifier +|$\n?)
I'm not sure where to start.
我不知道从哪里开始。
The actual code is:
实际代码是:
var re = top.RegExp;
var regex = new re("(.{1," + len + "})(+|$\n?)", "gm");
UPDATE:Per Bennor McCarthy's instructions, I changed the code to this:
更新:根据 Bennor McCarthy 的指示,我将代码更改为:
var regex = new re("(.{1," + len + "})(\+|$\n?)", "gm");
Firebug still tells me this:
Firebug 仍然告诉我这个:
invalid quantifier +|$\n?)
[Break on this error] var regex = new re("(.{1," + len + "})(\+|$\n?)", "gm");
ANOTHER UPDATELooks Like I had to double slash it and this solved the problem!
另一个更新看起来我不得不双斜线它解决了这个问题!
final code
最终代码
var regex = new re("(.{1," + len + "})(\+|\$\n?)", "gm");
回答by Bennor McCarthy
The problem is the +, which is a quantifier you need to escape.
问题是 +,这是您需要转义的量词。
Use this instead:
改用这个:
/(.{1,38})(\+|$\n?)/
or inside a string:
或在字符串内:
"(.{1,38})(\+|$\n?)"
If you want to match the literal $ followed by a newline, you need to escape the $ with \(or \\inside a string - see my last comment below this for an explanation).
如果要匹配文字 $ 后跟换行符,则需要将 $ 转义为\(或\\在字符串中 - 请参阅我在下面的最后一条评论以获取解释)。
Here's some information on quantifiers.
回答by Bryan Oakley
A quantifier means "how many". The most common is "*" which means zero or more. The quantifier "+" means one or more.
量词的意思是“多少”。最常见的是“*”,表示零个或多个。量词“+”表示一个或多个。
When you get an error about an illegal quantifier it almost always means you have a quantifier where it doesn't belong. For example, since they mean "how many" they must obviously refer to something. If you place one at the start of a pattern or group the regex is thinking "how many _of what?
当您收到关于非法量词的错误时,它几乎总是意味着您有一个不属于它的量词。例如,由于它们的意思是“多少”,因此它们显然必须指代某物。如果您将一个放在模式或组的开头,则正则表达式会考虑“有多少 _of 什么?
In your specific case you have a "+" immediately after the grouping character "(" which is why you get the error. You need to either escape the "+" so it isn't treated as a quantifier or put some character or group you want to match in front of it. In your case it is probably the first if you are trying to match an actual "+" character.
在您的特定情况下,您在分组字符“(”之后立即有一个“+”,这就是您收到错误的原因。您需要对“+”进行转义,以便它不被视为量词或放置一些字符或组你想在它前面匹配。在你的情况下,如果你试图匹配一个实际的“+”字符,它可能是第一个。

