REGEX:如何解析相同前缀文本中的可变数量的数据点

REGEX: How to parse a variable number of datapoints each inside the same prefixed text

本文关键字:数据 文本 何解析 前缀 REGEX      更新时间:2023-09-26

我有这个源数据

[画廊]标题[画廊项目]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演示。

虽然我确实希望它在某种程度上有用,但我也希望有人能过来,在笑了一会儿之后,告诉我如何简化这个怪物。。。