如何从字符串中获取json?

时间:2018-04-21 17:32:42

标签: regex

我有这个字符串:

"var block = new MatchesBlock('page_competition_1_block_competition_matches_summary_5', 'block_competition_matches_summary', {"page":0,"bookmaker_urls":{"13":[{"link":"http:\/\/www.bet365.com\/home\/?affiliate=365_178981","name":"Bet 365"}]},"block_service_id":"competition_summary_block_competitionmatchessummary","round_id":42011,"outgroup":false,"view":2,"competition_id":13});"

我想得到:

{"page":0,"bookmaker_urls":{"13":[{"link":"http:\/\/www.bet365.com\/home\/?affiliate=365_178981","name":"Bet 365"}]},"block_service_id":"competition_summary_block_competitionmatchessummary","round_id":42011,"outgroup":false,"view":2,"competition_id":13}

所以我写道:

MatchesBlock\(([^)]+)\)

但这会占用MatchesBlock

中的所有字符串

3 个答案:

答案 0 :(得分:0)

您可以使用默认情况下正则表达式贪婪并使用

的事实

MatchesBlock[^\{]+\K(.*})

我在这里使用\K重置匹配,即不会捕获\K之前的任何内容。

答案 1 :(得分:0)

如果您只想从MatchesBlock构造函数参数中提取JSON,只需使用以下正则表达式:

\{(?:[^{}]|(?R))*\}

输入:

var block = new MatchesBlock('page_competition_1_block_competition_matches_summary_5', 'block_competition_matches_summary', {"page":0,"bookmaker_urls":{"13":[{"link":"http:\/\/www.bet365.com\/home\/?affiliate=365_178981","name":"Bet 365"}]},"block_service_id":"competition_summary_block_competitionmatchessummary","round_id":42011,"outgroup":false,"view":2,"competition_id":13});

输出:

{"page":0,"bookmaker_urls":{"13":[{"link":"http:\/\/www.bet365.com\/home\/?affiliate=365_178981","name":"Bet 365"}]},"block_service_id":"competition_summary_block_competitionmatchessummary","round_id":42011,"outgroup":false,"view":2,"competition_id":13}

答案 2 :(得分:0)

对于提供的示例,您可以使用:

{[^)]+

enter image description here

Demo