匹配字符串中pattern的多个实例
Matching multiple instances of pattern in string
我试图将助手字符串(有点像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的现场演示
解释:
-
{{image:
: Match{{image:
literal -
[^}]*?
:不匹配}
-
}}
:匹配}}
文字
注意,用反引号括住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);
相关文章:
- ES6构造函数返回基类的实例
- KnockoutJS-组件-多个实例
- 为什么无法在TypeScript中导出类实例
- 如何在GoogleWeb工具包(GWT)中从JSNI调用接口(实例化)
- fluxxor向一个flux实例添加一组以上的操作
- 使用jQuery获取Dropzone实例/对象
- "实例范围”;TypeScript类的getter/setter
- 如何在速度模板中获取LiferayPortlet实例id
- 同一项怎么可能在一个实例中未定义,却在另一个实例上定义
- 实例创建(JS)
- 显示模块模式在Knockout中设置模型的新实例
- 如何获取单选按钮的多个实例的选定单选按钮值
- 当同一浏览器的两个实例浏览时,Javascript页面如何具有唯一的ID
- 在哪里可以找到RXUI Javascript'时间飞逝'实例
- spine.js在启动时填充模型实例
- 不再需要时使用jQuery/kill实例
- 如何在用户输入时实例化数组
- 从Sequelize中的非实例更新
- 如何基于数组值创建新实例
- 匹配字符串中pattern的多个实例