Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unterminated group in regexp

I try test string using regexp in JavaScript. Correct string looking like:

<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}

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

How can i parse script tag that looking like below?

like image 904
Andrew Kochnev Avatar asked Jan 28 '15 08:01

Andrew Kochnev


2 Answers

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]\}/
like image 52
Sébastien Avatar answered Oct 14 '22 06:10

Sébastien


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.

like image 24
Ynhockey Avatar answered Oct 14 '22 06:10

Ynhockey