[英]Regex: How to create an array of objects from all matches in javascript?
我正在嘗試獲取這樣的字符串輸入:
{p}This is a paragraph{/p} {img}(path/to/image) {p}Another paragraph{/p}
返回像這樣的對象數組
[
{"txt" : "This is a paragraph" },
{"img" : "path/to/image"},
{"txt" : "Another paragraph"}
]
我需要按照它們被找到的順序對數組進行索引 - 即在上面的例子中,第一段獲得索引0,圖像獲得索引1,依此類推。
我可以使用下面的代碼獲得很好的字符串,但我不確定如何修改它以遍歷整個字符串並將對象放在一起。 所以任何指針都將非常感激
var p = /{p}(.*){\/p}/gmi;
var i = /{img}\((.*)\)/gmi;
var test = "{p} This is a paragraph {/p} {img}(text)";
function returnJson(test) {
var ps = p.exec(test);
var im = i.exec(test)
var arr = [];
if (ps.length > 1) {
arr.push({"txt" : ps[1]})
}
if (im.length > 1) {
arr.push({"img" : im[1]})
}
return arr;
}
我正在考慮做一個遞歸函數,在那里我用字符串替換找到的匹配。 但后來我不確定如何按照發現的順序獲取數組。 任何提示非常感謝。
你可以使用這個正則表達式
/{(\w+)}([^{]+)(?:{\/\1})?/g
並使用exec
創建一個數組,如下所示:
let str = "{p}This is a paragraph{/p} {img}(path/to/image) {p}Another paragraph{/p}"; let regex = /{(\\w+)}([^{]+)(?:{\\/\\1})?/g; let match; let matches = []; while (match = regex.exec(str)) { if(match[1] == "p") matches.push({ txt: match[2] }) else matches.push({ [match[1]]: match[2]}) } console.log(matches)
{(\\w+)}
獲取捕獲組的標記名稱 ([^{]+)
將內容提取給另一個捕獲組 (?:{\\/\\1})?
可選地匹配結束標記。 ( \\1
指的是第一個捕獲組)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.