2015-01-21 129 views
3

在正則表達式中,如何查找以@symbol開頭的匹配項?符號不能位於單詞的中間(電子郵件地址中的鏈接)。正則表達式以@符號開頭

例如,看起來像這樣的字符串:

@someone's email is [email protected] and @someoneelse wants to send an email.

表達我用的是/^@[\w]/g

它應該返回:

@someone's

@someoneelse

我使用的表達式似乎不起作用。

+2

爲什麼要返回'@ someoneelse'?這是在字符串的中間(你說你不想要)。 – Thilo 2015-01-21 02:49:09

+0

我的意思是,在一個詞的中間是我的意思。 @Thilo – arjay07 2015-01-21 02:49:43

+3

好吧,'^'匹配字符串的開頭。如果你不想限制到字符串的開頭,你爲什麼使用'^'? – Eevee 2015-01-21 02:51:39

回答

4

您可以利用\B這是一個非單詞邊界,是\b否定版本。

var s = "@someone's email is [email protected] and @someoneelse wants to send an email.", 
    r = s.match(/\[email protected]\S+/g); 

console.log(r); //=> [ '@someone\'s', '@someoneelse' ] 
0
/(^|\s)@\w+/g 

[\w]只匹配一個字字符,所以這就是爲什麼你的正則表達式只返回@s\w+將匹配1個或更多單詞字符。

如果你想在該行裏面的字符串的開頭拿到的話,你可以用它執行字符串一個單詞的兩端開始一個空白字符之後的捕獲組(^|\s)

DEMO

var str="@someone's email is [email protected] and @someoneelse wants to send an email."; 
console.log(str.match(/(^|\s)@\w+/g)); //["@someone", " @someoneelse"] 
相關問題