[英]Regex: How to create an array of objects from all matches in javascript?
I'm trying to get a string input like this: 我正在尝试获取这样的字符串输入:
{p}This is a paragraph{/p} {img}(path/to/image) {p}Another paragraph{/p}
To return an array of objects like this 返回像这样的对象数组
[
{"txt" : "This is a paragraph" },
{"img" : "path/to/image"},
{"txt" : "Another paragraph"}
]
I need the array to be indexed by the order they are found – ie in the example above the first paragraph gets index 0, image gets index 1 and so forth. 我需要按照它们被找到的顺序对数组进行索引 - 即在上面的例子中,第一段获得索引0,图像获得索引1,依此类推。
I can get the strings great with the code below, but I am unsure how to modify it to loop through the entire string and put together the object. 我可以使用下面的代码获得很好的字符串,但我不确定如何修改它以遍历整个字符串并将对象放在一起。 So any pointers would be greatly appreciated
所以任何指针都将非常感激
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;
}
I was thinking of doing a recursive function, where I replace the found matches with the string. 我正在考虑做一个递归函数,在那里我用字符串替换找到的匹配。 But then I am unsure of how to get the array in the order they were found.
但后来我不确定如何按照发现的顺序获取数组。 Any tips greatly appreciated.
任何提示非常感谢。
You could use this regex 你可以使用这个正则表达式
/{(\w+)}([^{]+)(?:{\/\1})?/g
And create an array using exec
like this: 并使用
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+)}
gets the tag name to a capturing group {(\\w+)}
获取捕获组的标记名称 ([^{]+)
gets the content to another capturing group ([^{]+)
将内容提取给另一个捕获组 (?:{\\/\\1})?
optionally matches the closing tag. \\1
refers to the first capturing group) \\1
指的是第一个捕获组)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.