我有以下代码(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”,这正是我所期望的。任何人都可以对此有所了解吗?
提前致谢!
最佳答案
如果您正在使用 .exec
,您应该多次运行它以获得所有结果:
In the following example, the g (global) flag is set in the regular expression, so you can use exec() repeatedly to find multiple matches:
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
更好的选择可能是使用
String.match
:If pattern is a regular expression, in order to return an array with more than one matching substring, the g (global) flag must be set in the regular expression
一个例子应该是(未测试):
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);
关于RegEx 未找到所有匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8615611/