在javascript缩小文件上的正则表达式最小匹配

时间:2015-08-18 14:08:39

标签: javascript regex

我是一个缩小的文件。主要的特点是只有一行。

这可能是一个摘录:

bla();someothercode('resources/images/myPicture1.png'),someothercode('resources/images/myPicture2.png'),someothercode('resources/images/myPicture3.png');plop();

我试图抓住/\/(.*\.png)并获得:

myPicture1.png'),someothercode('resources/images/myPicture2.png'),someothercode('resources/images/myPicture3.png

而不是很多结果:

[myPicture1.png, myPicture2.png, myPicture3.png]

如何单独匹配所有png?

2 个答案:

答案 0 :(得分:3)

使用以下正则表达式:

\/([^\/]*\.png)

此处,\/匹配/,然后([^\/]*\.png)匹配并捕获PNG的名称(因为[^\/]*匹配除/以外的0个或更多字符,返回的匹配符合预期,预期值在组1)内。

参见代码:



var re = /\/([^\/]*\.png)/g; 
var str = 'bla();someothercode(\'resources/images/myPicture1.png\'),someothercode(\'resources/images/myPicture2.png\'),someothercode(\'resources/images/myPicture3.png\');plop();';
var m;
 
while ((m = re.exec(str)) !== null) {
    document.write(m[1] + "<br/>");
}
&#13;
&#13;
&#13;

答案 1 :(得分:1)

要抓住以.png结尾的所有“字词”,您可以说:

/\b[^\/]+\.png/g

这将找到文件名,无论是否有前面的/

var st = "bla();someothercode('resources/images/myPicture1.png'),someothercode('resources/images/myPicture2.png'),someothercode('resources/images/myPicture3.png');plop();";

var matches = st.match(/\b[^\/]+\.png/g);

console.log(matches);