繁体   English   中英

正则表达式,多次匹配一个单词

[英]Regexp, matching a word multiple times

这让我感到困惑,尽管我认为问题很简单。

给出这段代码:

var text   = ' url("https://") repeat scroll 0% 0%, url("https://") repeat scroll 0% 0%, url("https://") repeat scroll 0% 0% red';
var result = /(url)/.exec(text);

我得到的结果是["url", "url"] ..我期望在["url", "url", "url"]

任何解释为什么它只捕获2个url实例而不是3个实例

谢谢


更新接受的答案

实际上,这是我为HeadJS重写的Modernizr函数的一部分,因此最终函数将是:

function multiplebgs() {
    var ele   = document.createElement('div');
    var style = ele.style;

    style.cssText = 'background:url(https://),url(https://),red url(https://)';

    // If the UA supports multiple backgrounds, there should be three occurrences
    // of the string "url(" in the return value for elemStyle.background
    var result = (style.background || "").match(/url/g);

    return Object.prototype.toString.call( result ) === '[object Array]' && result.length === 3;
}

console.log(multiplebgs()); 现在将在受支持的浏览器上正确返回true。

如果有人发现其他问题,请发表评论,谢谢!

使用带有g标志的正则表达式match

var text   = ' url("https://") repeat scroll 0% 0%, url("https://") repeat scroll 0% 0%, url("https://") repeat scroll 0% 0% red';
var result = (text || "").match(/url/g);
result // => ["url", "url", "url"]

将您的正则表达式设为全局,然后使用match 您也不需要捕获组。

var result = text.match(/url/g);

exec与全局标志一起使用时,还将允许您获取所有匹配项,但是当您有多个捕获组时, exec会更加有用。 如果要获得与exec的所有匹配项,则必须执行以下操作:

var matches = [],
    urlRx = /url/g,
    match;

while (match = urlRx.exec(text)) {
    matches.push(match[0]);
}

console.log(matches);

第二行等效于您的情况:

'url url url'.match(/url/)    // ["url"]
'url url url'.match(/(url)/)  // ["url", "url"]
'url url url'.match(/url/g)   // ["url", "url", "url"]
'url url url'.match(/(url)/g) // ["url", "url", "url"] same as previous line

考虑到/(url)/ ,括号内的内容等效于“ sub regex”,称为子模式或组。 除了使用全局标志( //g )之外,每个组的捕获方式都与整个模式相同。 在这种情况下,将忽略组,并且捕获整个模式的次数与在文本中找到的次数相同。 这个例子将更加明确:

'hello world!hello world!'.match(/hello (world)(!)/)
// ["hello world!", "world", "!"]
// [entire pattern, group 1, group 2]

'hello world!hello world!'.match(/hello (world)(!)/g)
// ["hello world!", "hello world!"]
// [entire pattern, entire pattern]

在javascript中检查有关正则表达式的大量资源: http : //www.javascriptkit.com/javatutors/redev.shtml

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM