简体   繁体   English

正则表达式:在第一次出现和最后一次出现之间获取

[英]Regex: Get between first occurrence of one and last occurrence of another

This is the string: 这是字符串:

<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

How can I get only this part? 我怎样才能只得到这部分?

{
   "api_version": "1.0",
   "publisher": {
      "api_key": "some_api_key",
      "name": "Google Times"
   }
}

Can't really figure out this. 真的无法弄清楚。 The plan is to parse it JSON later. 计划是稍后将其解析为JSON。

First occurrence is { , second is } . 第一次出现是{ ,第二次出现是}

Curly braces. 大括号。

我认为可能是答案{(?:\\n|.)*}

If you are sure the braces can't be somewhere else then remove all new lines and use this: 如果您确定大括号不能在其他地方,请删除所有新行并使用以下命令:

var partYouNeed = yourString.match(/\{.*\}/)[0];

Example: 例:

 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!"); 

Here is the thing: 这是东西:

...
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); 
}

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

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