RegEx 未找到所有匹配项

标签 regex actionscript-3

我有以下代码(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/

相关文章:

java - 使用正则表达式更新保留字(有异常(exception))

javascript - 在 actionscript 3.0 中使用函数创建对象

java - 字符串的悬挂元字符和正则表达式模式

java - 检测到符号后删除单词

regex - Visual Studio Code - 删除所有空白行 - 正则表达式

actionscript-3 - 在 YouTube Chromeless 播放器 API 上获取 MenuItem 类缺失错误

javascript - 我需要将元 header 添加到 flex3 中的 URLRequest

MySQL。我讨厌正则表达式。只需要一个告诉我字符串是否以数字开头

flash - 为灰度图像着色 as3

actionscript-3 - if ( object != null ) 而不是 AS3 中的 if ( object )