匹配字符串中pattern的多个实例

Matching multiple instances of pattern in string

本文关键字:实例 pattern 字符串      更新时间:2023-09-26

我试图将助手字符串(有点像Stack的[enter link description here][1])保存到数据库,并在检索/查看时将其编译为HTML。一个示例文本是:

var str = 'This is just a sample text followed by an {{image: imageUrl1}}. And here is another {{image: imageUrl2}}.';

我尝试了以下RegEx:

str.match(`/('{'{image:)[^(.*'}'})]*.*('}'})/g`);

但我只得到["{{image: imageUrl1}}. And here is another {{image: imageUrl2}}"]

什么应该是RegEx模式,使结果是["{{image: imageUrl1}}", "{{image: imageUrl2}}"] ?

正则表达式是贪婪的(匹配所有可能的结果以满足条件)。这意味着,正则表达式将匹配从{{到最后一个}}的字符串。若要只匹配到第一个}}符号,可以在*量词后添加?量词,使其变为惰性。

/{{image:[^}]*?}}/g

下面是RegEx101的现场演示

解释:

  1. {{image:: Match {{image: literal
  2. [^}]*?:不匹配}
  3. }}:匹配}}文字

注意,用反引号括住regex使其成为字符串。使用regex文字语法

var str = 'This is just a sample text followed by an {{image: imageUrl1}}. And here is another {{image: imageUrl2}}.';
var matches = str.match(/{{image:[^}]*?}}/g);
console.log(matches);


要提取URL,使用捕获组并获得第一个捕获组。

/{{image:'s*([^}]*?)}}/

var str = 'This is just a sample text followed by an {{image: http://someURLHERE.domain}}. And here is another {{image: imageUrl2}}.';
var regex = /{{image:'s*([^}]*?)}}/g;
var match = '';
var urls = [];
while (match = regex.exec(str)) {
    urls.push(match[1]);
}
console.log(urls);