javascript 正则表达式中的未终止组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28187300/
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
Unterminated group in regexp
提问by Andrew Kochnev
I try test string using regexp in JavaScript. Correct string looking like:
我尝试在 JavaScript 中使用正则表达式测试字符串。正确的字符串看起来像:
<script charset="utf-8">new DGWidgetLoader({"width":640,"height":600,"borderColor":"#a3a3a3","pos":{"lat":46.00650100065259,"lon":11.263732910156252,"zoom":9}
I want test that "width", "height" looks like xxx or xxxx, and "lat", "lon" looks like x{1,2}.x*, zoom looks like x{1,2}
我想测试“宽度”,“高度”看起来像 xxx 或 xxxx,“纬度”,“经度”看起来像 x{1,2}.x*,缩放看起来像 x{1,2}
I try use this regex
我尝试使用这个正则表达式
/<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]}//
with String.search(), but got error 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
使用 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
How can i parse script tag that looking like below?
我如何解析如下所示的脚本标签?
回答by user3409662
You should escape (
, {
, }
and .
with \
:
你应该逃避(
,{
,}
并.
用\
:
/<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]\}/
回答by Ynhockey
I think the problem is here:
我认为问题出在这里:
... DGWidgetLoader(/{ ....
Should be:
应该:
... DGWidgetLoader\(\{ ...
And the final slash is unnecessary in this case.
在这种情况下,最后的斜线是不必要的。
EDIT: Also, escape the final } mark and other special characters. So:
编辑:另外,转义最后的 } 标记和其他特殊字符。所以:
/<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]\}/
Also there is a small logic issue here: your zoom rule requires exactly two numerals while in practice it can be either one or two. You should consider fixing that.
这里还有一个小逻辑问题:您的缩放规则正好需要两个数字,而实际上它可以是一个或两个。你应该考虑解决这个问题。