这是字符串:
<html lang=3D"en-US"> <head> </head> <body> <div> <script data-scope=3D"in=
boxmarkup" type=3D"application/json">
{
"api_version": "1.0",
"publisher": {
"api_key": "some_api_key",
"name": "Google Times"
}
}
sdalfk jsdklfj slkdjf lskdjfl sjdlkf jsdlkj flsdkj flsdk jf
我怎样才能获得这部分?
{
"api_version": "1.0",
"publisher": {
"api_key": "some_api_key",
"name": "Google Times"
}
}
无法弄清楚这一点。计划是稍后解析JSON。
第一次出现是{
,第二次是}
。
大括号。
答案 0 :(得分:2)
我认为this可能是答案{(?:\n|.)*}
答案 1 :(得分:0)
如果你确定括号不能在其他地方,那么删除所有新行并使用它:
var partYouNeed = yourString.match(/\{.*\}/)[0];
示例:强>
var str =
'<html lang=3D"en-US"> <head> </head> <body> <div> <script data-scope=3D"in=\
boxmarkup" type=3D"application/json">\
{\
"api_version": "1.0",\
"publisher": {\
"api_key": "some_api_key",\
"name": "Google Times"\
}\
}\
sdalfk jsdklfj slkdjf lskdjfl sjdlkf jsdlkj flsdkj flsdk jf';
var result = str.replace(/\n|\r/g, '') // remove all newlines
.match(/\{.*\}/); // match anything inside curly braces
if(result)
console.log(result[0]);
else
console.log("nothing found!");
&#13;
答案 2 :(得分:0)
事情就是这样:
...
myString = myString.replace(/\s/g,'');
var jsonRegex = /.*{(.*)}.*/g;
var match = jsonRegex.exec(myString);
var jsonStr = match[1];
var myObject;
try {
myObject = JSON.parse(jsonStr);
} catch (JSONException) {
console.log('Error while parsing data: ', JSONException);
}