JavaScript-Regex-Grab-only matched模式,如果一行中有多个匹配项
我正在尝试读取CSS文件的内容,并查找指向外部文件的所有链接。我想写一个快速的正则表达式来为我做这件事会更快,然而这被证明是令人沮丧的 假设我有:JavaScript-Regex-Grab-only matched模式,如果一行中有多个匹配项,javascript,regex,Javascript,Regex,我正在尝试读取CSS文件的内容,并查找指向外部文件的所有链接。我想写一个快速的正则表达式来为我做这件事会更快,然而这被证明是令人沮丧的 假设我有: @font-face{font-family:'FontAwesome';src:url('../fonts/fontawesome-webfont.eot?v=4.6.3');src:url('../fonts/fontawesome-webfont.eot?#iefix&v=4.6.3') format('embedded-opentyp
@font-face{font-family:'FontAwesome';src:url('../fonts/fontawesome-webfont.eot?v=4.6.3');src:url('../fonts/fontawesome-webfont.eot?#iefix&v=4.6.3') format('embedded-opentype'),url('../fonts/fontawesome-webfont.woff2?v=4.6.3') format('woff2'),url('../fonts/fontawesome-webfont.woff?v=4.6.3') format('woff'),url('../fonts/fontawesome-webfont.ttf?v=4.6.3')
这句话还有点长,但现在就让我们来看看吧
如您所见,这里既有src:url(…)
也有url(…)
,所以我想我可以只查找url(…)
出现的情况
以下是我尝试过的:
以1为例:
第二个例子:
var contents.match = ... // The contents of the .min.css file.
var matches = contents.match(/url\s*(.*);/); //no g at the end.
第三个例子:
var contents.match = ... // The contents of the .min.css file.
var matches = contents.match(/url\s*\((.*)\);/g);
以4为例:
var contents.match = ... // The contents of the .min.css file.
var matches = contents.match(/url\s*\((.*)\);/); // no g at the end.
我想要的只是一个包含所有匹配项的数组,要么是()之间的字符串,要么是整个匹配项,即url(…);相反,我只是从整个文件中取出一个大管道
我想要的是:
console.log(matches); /// Prints ['fonts/font_1.css', 'fonts/font_2.css', 'fonts/font_3.css']
的
我在哪里错过了什么?在我看来,你好像错过了什么?在你的表情中。与此相反:
contents.match(/url\s*\(.*\);/g)代码>
试着这样做:
contents.match(/url\s*\(.*?\);/g)代码>
您当前正在匹配的是url的第一个实例(到的最后一个实例)。的*
是一个问题,因为它也将匹配结束参数
试试这个:/url\s*\([^)]*\)/g
*
将匹配
表示匹配将一直延续到最后一个代码>它找到了。请尝试[^;]+
而不是*
。注意:在测试正则表达式时,像这样的网站非常有用(请记住相应地设置其风格),请尝试/url\(*?)/g
console.log(matches); /// Prints ['fonts/font_1.css', 'fonts/font_2.css', 'fonts/font_3.css']
console.log(matches); /// Prints ["url(fonts/font_1.css')", "url('fonts/font_2.css')", "url('fonts/font_3.css')"]