匹配字符串中的多个模式实例

时间:2016-10-07 02:59:37

标签: javascript regex

我正在尝试将帮助字符串(有点像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}}"]

1 个答案:

答案 0 :(得分:1)

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

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

此处在RegEx101上直播demo

<强>解释

  1. {{image::匹配{{image:文字
  2. [^}]*?:除} lazily
  3. 之外的任何内容
  4. }}:匹配}}文字
  5. 请注意,通过反向标记围绕正则表达式使其成为字符串。使用正则表达式文字语法。

    &#13;
    &#13;
    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);
    &#13;
    &#13;
    &#13;

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

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

    &#13;
    &#13;
    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);
    &#13;
    &#13;
    &#13;

相关问题