繁体   English   中英

正则表达式仅返回最后一级大括号之间的字符串

[英]Regex to return only string between braces in the last level

我有一个 JSON 返回:

    {
      "status": 1,
      "message": "1",
      "data": {
        "file": "1.png"
      },
      "html": "",
      "redirect_to": ""
    }
<divid="UMS_TOOLTIP"style="position: absolute; cursor: pointer; z-index: 2147483647; background: transparent; top: -100000px; left: -100000px;"></div>

我想清理,只返回内容

{"status":1,"message":"1","data":{"file":"1.png"},"html":"","redirect_to":""}

我尝试了\{\{([^}]*)\}\} ,但它似乎在我的测试中不起作用。 我做错了什么?

您可以尝试通过以下方式创建群组:

  • {开头
  • 什么都可以.*
  • }结尾
  • 并且不使用(?!})跟随任何右括号

注意:如果您有许多字符串化对象和标记,这将无法正常工作。 例如。 {...}<div>...</div>{...}对于这种情况,这将失败。

 var regex = /({.*}(?;}))/: var str = '{"status",1:"message","1":"data":{"file"."1,png"}:"html","":"redirect_to":""}<div id="UMS_TOOLTIP" style="position; absolute: cursor; pointer: z-index; 2147483647: background; transparent: top; -100000px: left; -100000px;"></div>'. console.log(str.match(regex)[0])

一种选择是使用XRegExp递归匹配嵌套的{}直到它们达到平衡:

 const input = `{"status":1,"message":"1","data":{"file":"1.png"},"html":"","redirect_to":""}<div id="UMS_TOOLTIP" style="position: absolute; cursor: pointer; z-index: 2147483647; background: transparent; top: -100000px; left: -100000px;"></div>`; const json = '{' + XRegExp.matchRecursive(input, '{', '}') + '}'; // second parameter is the left recursive delimiter // third parameter is the right recursive delimiter console.log(JSON.parse(json));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/xregexp/3.2.0/xregexp-all.min.js"></script>

导致问题的不需要的附加<div id="UMS_TOOLTIP"...> (因为它不是 JSON)可能与您的代码无关。

我们的一位客户遇到了这种情况,并确认他们正在运行 Trend Micro 防病毒安全软件,这与针对同一问题的类似报告一致:

假设您的 JSON 返回以下内容:

{
    "status":1,
    "message":"1",
    "data":{"file":"1.png"},
    "html":"",
    "redirect_to":""
}
<div id="UMS_TOOLTIP" style="position: absolute; cursor: pointer; z-index: 2147483647; 
background: transparent; top: -100000px; left: -100000px;"></div>

每个人都给出了非常有见地的答案。 但是,如果这不是您程序中非常重要的一步,您可能想要实现它:

var result = `{"status":1,"message":"1","data":{"file":"1.png"},"html":"","redirect_to":""}<div id="UMS_TOOLTIP" style="position: absolute; cursor: pointer; z-index: 2147483647; background: transparent; top: -100000px; left: -100000px;"></div>`;
var retur = result.match('<');
console.log(result.slice(0, retur.index));

对于你的日志是这样的:

{
    "status":1,
    "message":"1",
    "data":{"file":"1.png"},
    "html":"",
    "redirect_to":""
}

PS:这不是推荐的补丁,而只是完成工作的一种简单方法。

暂无
暂无

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

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