2012-07-12 80 views
0

我是一名Javascript初學者,正在玩正則表達式。簡單的正則表達式問題

我試圖執行一些匹配操作,但結果相當混亂。

所有我想要做的是在每一個網站的名稱相匹配:

「我去google.com搜索,到facebook.com分享和yahoo.com發送電子郵件。」

這裏是我的代碼:

var text = "I go to google.com to search, to facebook.com to share and to yahoo.com to send an email."; 
var pattern = /\w+\.\w+/g; 

var matches = pattern.exec(text); 

document.write("matches index : " + matches.index + "<br>"); 
document.write("matches input : " + matches.input + "<br>"); 
document.write("<br>"); 
for(i=0 ; i<matches.length ; i++){ 
    document.write("match number " + i + " : " + matches[i] + "<br>"); 
} 

而且我的結果:

匹配指數:0

匹配輸入:我去到google.com搜索,到Facebook。 com分享 併發送至yahoo.com發送郵件

匹配號碼0:google.com

爲什麼它匹配google.com只,而不是其他網站?

+0

的可能重複(HTTP://計算器。 com/questions/6323417/how-do-i-retrieve-all-matches-for-a-regular-expression-in-javascript) – 2012-07-12 00:39:55

回答

1

MDN documentation

如果你的正則表達式使用「g」標誌,就可以使用exec方法多次找到相同的字符串匹配連續。當您這樣做時,搜索開始於由正則表達式的lastIndex屬性指定的子字符串strtest也將提前lastIndex屬性)。

所以,只要執行它多次:

var match, i = 0; 
while(match = pattern.exec(text)) { 
    document.write("match number " + (i++) + " : " + match[0] + "<br>"); 
} 

,或者因爲你沒有捕捉組,使用.match()

var matches = text.match(pattern); 
for(i=0 ; i<matches.length ; i++){ 
    document.write("match number " + i + " : " + matches[i] + "<br>"); 
} 
+0

嗯,雖然很奇怪。在[適用於Web開發人員的專業Javascript](http://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691/ref=pd_sim_b_1)書中。有一個例子[這裏](http://jsfiddle.net/smokn/gzAVS/)只使用exec一次。而它的奇怪的事情,它的作品! – 2012-07-12 00:50:08

+0

@Rafael - 你的小提琴中的例子使用捕獲組'(...)' – 2012-07-12 00:55:17

+0

在你的最後一個例子中,當沒有匹配時,for循環會產生一個錯誤。所以最好檢查'匹配'是否先不爲空。 – inhan 2012-07-12 01:01:14

0

我只是想提的是,替代方法有時更適合遍歷字符串,即使您實際上並不打算替換任何東西。

這裏是它如何工作你的情況:我如何檢索在JavaScript中的正則表達式所有匹配]

var matches = text.replace(pattern,function($0){alert($0);}); 

Live demo here