2011-12-23 90 views
4

我有以下代碼(AS3 & CS 5.5):正則表達式沒有找到匹配的所有

var regEx:RegExp = new RegExp(/(?:^|\s)(\#[^\s$]+)/g); 
var txt:String = "This #asd is a test tweet #hash1 test #hash2 test"; 

var matches:Object = regEx.exec(txt); 
trace(matches); 

跟蹤返回 '#ASD,ASD#'。我真的不明白爲什麼會這樣,因爲在我的RegEx測試應用程序'RegExhibit'中它返回'#asd,#hash1,#hash2',這正是我所期望的。任何人都可以對此有所瞭解嗎?

在此先感謝!

回答

6

如果您正在使用.exec,您應該多次運行它得到的所有結果:

在下面的例子中,g(全局)標誌的正則表達式,所以你可以使用EXEC反覆()來找到多個匹配:

var myPattern:RegExp = /(\w*)sh(\w*)/ig; 
var str:String = "She sells seashells by the seashore"; 
var result:Object = myPattern.exec(str); 

while (result != null) { 
    trace (result.index, "\t", result); 
    result = myPattern.exec(str); 
} 

來源:http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/RegExp.html

更好的選擇是PR obably使用String.match

如果圖案是正則表達式,爲了返回與多於一個的匹配子串的陣列,g(全局)標誌必須在正則表達式來設定

一個例子應該是(未測試):

var regEx:RegExp = /(?:^|\s)(\#[^\s$]+)/g; 
var txt:String = "This #asd is a test tweet #hash1 test #hash2 test"; 

var matches:Object = txt.match(regEx); 
相關問題