正则表达式中未终止的组

时间:2015-01-28 08:01:21

标签: javascript regex parsing

我在JavaScript中使用regexp尝试测试字符串。 正确的字符串看起来像:

<script charset="utf-8">new DGWidgetLoader({"width":640,"height":600,"borderColor":"#a3a3a3","pos":{"lat":46.00650100065259,"lon":11.263732910156252,"zoom":9}

我想测试“宽度”,“高度”看起来像xxx或xxxx,以及“lat”,“lon” 看起来像x {1,2} .x *,缩放看起来像x {1,2}

我尝试使用此正则表达式

/<script charset="utf-8">new DGWidgetLoader(/{"width":[0-9]{3,4},"height":[0-9]{3,4},"borderColor":"#a3a3a3","pos":\{"lat":[0-9]{1,2}.[0-9]+,"lon":[0-9]{1,2}.[0-9]+,"zoom":[0-9][0-9]}//

使用String.search(),但收到错误SyntaxError: Invalid regular expression: /<script charset="utf-8">new DGWidgetLoader(/{"width":[0-9]{3,4},"height":[0-9]{3,4},"borderColor":"#a3a3a3","pos":{"lat":[0-9]{1,2}.[0-9]+,"lon":[0-9]{1,2}.[0-9]+,"zoom":[0-9][0-9]}//: Unterminated group

我如何解析如下所示的脚本标记?

2 个答案:

答案 0 :(得分:10)

您应该使用(转义{}.\

/<script charset="utf-8">new DGWidgetLoader\(\{"width":[0-9]{3,4},"height":[0-9]{3,4},"borderColor":"#a3a3a3","pos":\{"lat":[0-9]{1,2}\.[0-9]+,"lon":[0-9]{1,2}\.[0-9]+,"zoom":[0-9][0-9]\}/

答案 1 :(得分:2)

我认为问题在于:

... DGWidgetLoader(/{ ....

应该是:

... DGWidgetLoader\(\{ ...

在这种情况下,最后的斜线是不必要的。

编辑:此外,逃避最终的}标记和其他特殊字符。所以:

/<script charset="utf-8">new DGWidgetLoader\(\{"width":[0-9]{3,4},"height":[0-9]{3,4},"borderColor":"#a3a3a3","pos":\{"lat":[0-9]{1,2}\.[0-9]+,"lon":[0-9]{1,2}\.[0-9]+,"zoom":[0-9][0-9]\}/

此处还存在一个小的逻辑问题:缩放规则只需要两个数字,而实际上它可以是一个或两个。你应该考虑修复它。