簡體   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