JavaScript:正则表达式中的无效量词 [英] JavaScript: Invalid quantifier in regex

查看:355
本文介绍了JavaScript:正则表达式中的无效量词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正则表达式是动态构建的,但我已将其输出到firebug:

The regex is constructed on the fly, but I've output it to firebug:

(.{1,38})(+|$\n?)

错误是

invalid quantifier +|$\n?)

我不知道从哪里开始。

实际代码是:

var re = top.RegExp;
var regex = new re("(.{1," + len + "})(+|$\\n?)", "gm");

更新:
根据Bennor McCarthy的说明,我更改了代码:

UPDATE: Per Bennor McCarthy's instructions, I changed the code to this:

 var regex = new re("(.{1," + len + "})(\+|\$\\n?)", "gm");

Firebug仍告诉我:

Firebug still tells me this:

invalid quantifier +|$\n?)
[Break on this error] var regex = new re("(.{1," + len + "})(\+|\$\\n?)", "gm"); 

另一个更新
看起来我不得不双击它这解决了这个问题!

ANOTHER UPDATE Looks Like I had to double slash it and this solved the problem!

var regex = new re("(.{1," + len + "})(\\+|\\$\\n?)", "gm");


推荐答案

问题是+,这是量词你需要逃避。

The problem is the +, which is a quantifier you need to escape.

请改用:

/(.{1,38})(\+|$\n?)/

或在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).

这里有一些有关量词的信息

这篇关于JavaScript:正则表达式中的无效量词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆