2013-10-24 20 views
1
var test = "Hello all, this is a message and i want to mention @john, @smith and @jane..."; 

,我希望得到的是:拆分多個單詞開始用@符號

var result = ["john", "smith", "jane"]; 

我可以把最後一個用戶名字符串,但不是所有的人英寸對於正則表達式或其他字符串函數,我沒有問題。

謝謝。

+0

@Joren id idnt實際上嘗試了很多。我看到另一個問題,只能從字符串中獲得一個值。 – alix

回答

1

看來,它使用一個單一的正則表達式是不可能的:

var result = test.match(/@\w+/g).join('').match(/\w+/g); 

您可能需要處理的情況,其中,正則表達式找不到:

var result = test.match(/@\w+/g); 
result = result ? result.join('').match(/\w+/g) : []; 
+0

我仍然有信心,有一天我會學習正則表達式。它總是對我來說太複雜了。順便說一句,謝謝。這也起作用。 – alix

+1

@AliOguzhanYildiz這是一個很好的起點:http://www.javascriptkit.com/javatutors/redev.shtml。 – leaf

1

試試這個正則表達式

/(^|\W)@\w+/g 

的JavaScript:

var test = "Hello all, this is a message and i want to mention @john, @smith and @jane"; 
var names = test.match(/(^|\W)@\w+/g); 
console.log(names); 

結果:

0: "@john" 
1: "@smith" 
2: "@jane" 

活生生的例子在RegExrhttp://regexr.com?36t6g

+0

謝謝。但是這給了我名字「@jonh」, – alix

+0

啊哈,對不起!我已經更新了正則表達式:) – subZero

+0

我想要沒有@符號的名稱。純粹。但我也很確定。我可以處理休息。再次感謝:) – alix

1
var test = "Hello all, this is a message and i want to mention @john, @smith and @jane..."; 
var patt = /(^|\s)@([^ ]*)/g; 
var answer = test.match(patt) 

應該得到你想要的

喜歡這個JSfiddle

+0

謝謝,但與上面相同。這給名稱爲「@ john」,「@jane ...」 – alix