我有这个源数据
[画廊]标题[画廊项目]http://www.google.com/image.jpg[/galleryitem][画廊项目]http://www.google.com/image.jpg[/galleryitem][画廊项目]http://www.google.com/image.jpg[/galleryitem][画廊项目]http://www.google.com/image.jpg[/galleryitem][画廊项目]http://www.google.com/image.jpg[/galleryitem][画廊项目]http://www.google.com/image.jpg[/galleryitem][/gallery]
现在的工作方式是,这是一个图库框,它以图库框的标题开头,后面是一系列封装图像URL的[galleryitem]标签。
问题是,这些galleryitem图像中会有一个变量#,所以我无法找到通过regex处理这一问题的方法。
理想情况下,我会把所有的图像都匹配成某种数组,我可以在单个数组中循环处理。这一切都是在Javascript BTW中完成的。
您需要一次提取一个匹配项。这是我通常使用的模式:
var bbcode = "...";
var pattern = /[galleryitem]([^[]*)[/galleryitem]/g;
var match, url;
while (match = pattern.exec(bbcode)) {
url = match[1];
// do something with url
}
这是怎么回事?RegExp对象(pattern
)在字符串中跟踪其当前索引,每次调用exec
时,它都会从存储的索引开始搜索下一个匹配项。当没有匹配项时,exec
返回null,循环终止。
RegExp.exec()
。
function getGalleryItems(str) {
var matches = [],
galleryitems = [],
re = /[galleryitem]([^[]*)[/galleryitem]/g;
while (matches !== null) {
matches = re.exec(str);
if (matches !=== null) {
galleryitems.push(matches[1]);
}
}
return galleryitems;
}
我仍然(显然…)是regex的新手,但我想到了以下内容:
var text = "[gallery]Title[galleryitem]http://www.google.com/image.jpg[/galleryitem][galleryitem]http://www.google.com/image.jpg[/galleryitem][galleryitem]http://www.google.com/image.jpg[/galleryitem][galleryitem]http://www.google.com/image.jpg[/galleryitem][galleryitem]http://www.google.com/image.jpg[/galleryitem][galleryitem]http://www.google.com/image.jpg[/galleryitem][/gallery]";
var parsedText = text.replace(/([/*galleryitem])|([/*gallery])|title/gi,' ').split(/s+/);
var imgs = [];
for (var i=0,len=parsedText.length;i<len;i++){
if (parsedText[i] != ''){
imgs.push(parsedText[i]);
}
}
console.log(imgs);
JS Fiddle演示。
虽然我确实希望它在某种程度上有用,但我也希望有人能过来,在笑了一会儿之后,告诉我如何简化这个怪物。。。