我有一个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
递归匹配嵌套的{
和}
s,直到它们平衡:
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>
假设,您的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:这不是推荐的补丁,但只是完成工作的一种简单方法。