簡體   English   中英

查找所有正則表達式匹配

[英]Find all regex matches

每個人都告訴我,如果我有一個像/blah/g這樣的正則表達式,並且我在一個字符串上反復exec它,那么我將經歷所有的匹配,直到結束為止。

但是,如果我的正則表達式是/^$/g而我的字符串是""怎么辦? 那是什么?

這工作正常:

var re = /bar/g,
    str = "foobarfoobar";
while ((match = re.exec(str)) != null) {
    alert("match found at " + match.index);
}

這進入了無限循環!

var re = /^$/g,
    str = "";
while ((match = re.exec(str)) != null) {
    alert("match found at " + match.index);
}

為什么使用Javascript? 為什么?

(更重要的是,如果我的正則表達式包含^$並且我的字符串可能是空字符串,那么我應該如何遍歷正則表達式的匹配項?)

此處的問題是由於JS正則表達式引擎在匹配空字符串時不推進其索引而導致的。 您可以使用一些其他代碼(摘自regex101.com示例代碼生成器頁面)“手動”移動它:

 var re = /^$/g; var str = ''; if ((m = re.exec(str)) !== null) { if (m.index === re.lastIndex) { // Here you manually advance re.lastIndex++; // the index } alert(m[0]); } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM