2012-07-12 76 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