简体   繁体   English

正则表达式解析对象文字

[英]Regex For Parsing Object Literal

Im trying to parse out a JavaScript object literal from a script block on a page. 我试图从页面上的脚本块解析出JavaScript对象文字。 Here's the example I have of the data: 这是我的数据示例:

//End Update for CASE00370003 2011/08/22
stores[0] = {
'fullName' : 'Bobs Commons',
'street1' : '23 Chestnut Commons Dr'
};
//Some more comments
stores[1] = {
'fullName' : 'Gove Wood',
'street1' : '65 Lake Rd'
};

So far I've come up with: 到目前为止,我已经提出了:

/^(stores\[)(\d){1,2}(])(.|\n)*};$/m

However, the string ends with "};" 但是,字符串以“};”结尾 will grab the last occurrence of the }; 将获取}的最后一次出现; on stores[1], so each won't be broken individually. 在stores [1]上,因此每个不会被单独破坏。 Thanks! 谢谢!

Seems that what you need is 'non-greedy' matches ( *? instead of * ) - it captures the shortest match rather than the longest. 似乎您需要的是“非贪婪”匹配( *?而不是* )-它捕获最短的匹配而不是最长的匹配。 So the regex will look like: 因此,正则表达式将如下所示:

/^(stores\[)(\d){1,2}(])(.|\n)*?};$/m

After suggesting that I still have to note that you in general should not do that with regular expressions at all :). 在建议我之后,我仍然必须指出,一般而言,您根本不应该使用正则表达式:)。 Your approach will break if the object string properties contain '}' (eg, 'fullName' : 'Bobs Comm}ons'). 如果对象字符串属性包含“}”(例如,“ fullName”:“ Bobs Comm} ons”),则您的方法将会中断。

Additionally to the @amakhrov answer above: 除了上述@amakhrov答案之外:

you may perform consecutive searches of closing curly brace unless JSON.parse(literal_string); 您可以连续搜索大括号,除非JSON.parse(literal_string); executes without exceptions 无例外地执行

UPD: missed the important fact, that for that it needs to be a valid JSON UPD:错过了重要的事实,那就是它必须是有效的JSON

PREPARE TO HAVE YOUR MIND BLOWN. 准备好接受您的建议。

JSON (the thing several answers have mentioned) ---> JSON(有几个答案提到的东西)--->

J ava- S cript O bject N otation. Ĵava- 小号 CRIPTöbjectÑ浮选。

Cool, right? 酷吧? Since JS' declaration syntax is so useful, it became a neutral data format. 由于JS的声明语法非常有用,因此它成为一种中性的数据格式。 That's the format your web request is returning, and JavaScript even has special libraries for parsing it. 这就是您的Web请求返回的格式,JavaScript甚至具有用于解析它的特殊库。 I think you may have just been unclear on that part. 我认为您可能对此尚不清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM