使用Javascript / JQuery在两个字符串模式之间提取子字符串

时间:2015-01-21 01:59:21

标签: javascript jquery regex

我是正则表达的新手。我需要在两个字符串模式之间提取( [[tag :: & ]] )以及每次出现。

例如:

如果文字是:

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus [[tag::4797897]] mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu.
[[tag::4797800]] [[tag::4797769]]

由于我想要 [[tag :: ]] 之间的提取文字,预期输出应为4797897,4797800和4797769

我正在使用Javascript和JQuery

有些人可以帮助我。提前致谢

2 个答案:

答案 0 :(得分:1)

要获得所需的结果,您可以在循环中使用exec()方法,将capturing组的匹配结果推送到结果数组。

var str = ' ... '
var re  = /\[\[tag::([^\]]+)]]/g, 
matches = [];

while (m = re.exec(str)) {
  matches.push(m[1]);
}

console.log(matches) //=> [ '4797897', '4797800', '4797769' ]

答案 1 :(得分:0)

使用capturing groups

\[\[tag::(.*?)]]

从组索引1中获取所需的值。.*?将执行零个或多个字符的非贪婪匹配。 [是一个正则表达式元字符,表示字符类的开头。因此,您需要在正则表达式中依次转义[以匹配文字[符号。

DEMO

> var str = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus [[tag::4797897]] mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu.\nLorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus [[tag::4797897]] mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu.\n[[tag::4797800]] [[tag::4797769]]"
> var re = /\[\[tag::(.*?)]]/g;
> while (m = re.exec(str)) {
... match.push(m[1]);
... }
> console.log(match)
[ '4797897', '4797800', '4797769' ]