[英]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.