为什么RegExp会产生“意外量词”的错误。在IE8上? [英] Why RegExp generates an error of "unexpected quantifier" on IE8?

查看:797
本文介绍了为什么RegExp会产生“意外量词”的错误。在IE8上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Javascript错误已经报告给我,不幸的是我不知道如何重现它。 IE8 Developer Tools报告以下错误:意外的量词。以下行产生错误:

I have a Javascript error that have been reported to me and unfortunately I've no idea on how to reproduce it. IE8 Developer Tools reports the following error: Unexpected quantifier. The following row produces the error:

var g=RegExp(d+"=([^|]*)").exec(j); //output from closure-compiler

我想我必须正确地逃避管道( \\ | )解决问题,但我不知道我是否正确,因为我不知道如何重现错误。

I guess I have to escape properly the pipe like that (\\|) to fix the problem, but I don't know if I'm right because I don't know how to reproduce the error.

欢迎任何建议或解决方案。

Any suggestions or solutions are welcome.

谢谢。

[更新]

d 的值是 __ utmz 我正在尝试检索的cookie值,它们列在这样的数组中 [utmccn,utmcmd,/ * ... * /] 。好吧,现在我没有那么多可以做,我和我的朋友在家里流感。

The values of d are the keys of __utmz cookie values which I'm trying to retrieve and they are listed in an array like this ["utmccn", "utmcmd", /* ... */]. Well now there's not so much I can do, I'm at home with my friend the flu.

推荐答案

量词是一个正则表达式运算符,如 * + 。上面代码中的变量d可能包含一些被解释为正则表达式解析器的代码的东西,它是无效的。你是对的,它需要被适当地转义。这是一个非常类似于转义包含在HTML标记中的文本问题的问题,但是因为所讨论的语法完全不同(即正则表达式语法与HTML语法)而不同。

A "quantifier" is a regular expression operator like * or +. The variable "d" in the above code probably contains something that's being interpreted as "code" to the regular expression parser, and it's invalid. You're right that it needs to be appropriately escaped. It's a problem very similar to the problem of escaping text that's being included in HTML markup, but distinct because the syntax in question is completely different (that is, regular expression syntax vs. HTML syntax).

显然,正则表达式语法中有很多特殊字符,所以这需要一个非常粗糙的正则表达式。这是一种可行的方法:

There are a lot of special characters in regular expression syntax, obviously, so it'll take a pretty gnarly regex to do that. Here's a possible way to do such a thing:

var quoted = unquoted.replace(/([*+.?|\\\[\]{}()])/g, '\\$1');

这可能无法全部获得;我会四处查看代码,这些代码比我刚刚组成的涂料更加经过测试: - )

That might not get all of them; I'd look around for code that's more definitely tested than something a dope like me just made up :-)

由于您发布的代码看起来可能来自某些代码库,您可能需要检查IE调试器中的堆栈跟踪以找出问题的起始位置。

Since that code you posted looks like it may come from some library, you may want to check the stack trace from the IE debugger to find out where the problem starts.

这篇关于为什么RegExp会产生“意外量词”的错误。在IE8上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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