Actionscript RegExp 在一次调用中定位所有匹配项的位置和长度



如何使用 actionscript 中的正则表达式在一次调用中定位文本中某个单词的所有位置。

例如,我有这个正则表达式:

var wordsRegExp:RegExp = /[^a-zA-Z0-9]?(include|exclude)[^a-zA-Z0-9]?/g;

它在文本中找到"包括"和"排除"这两个词。

我正在使用

var match:Array;
match = wordsRegExp.exec(text)
找到单词

,但它首先找到第一个单词。我需要找到所有单词"包括"和"排除"以及位置,所以我这样做:

    var res:Array = new Array();
    var match:Array;
    while (match = wordsRegExp.exec(text)) {
        res[res.length]=match;
    }

这确实可以解决问题,但对于大量文本来说非常非常慢。我正在寻找其他方法,但没有找到。

请提前提供帮助和感谢。

EDIT: I tried var arr:Array = text.match(wordsRegExp);
it finds all words, but not there positions in string

我认为这就是野兽的本性。我不知道你说的"大量文本"是什么意思,但如果你想要更好的性能,你应该编写自己的解析函数。这不应该那么复杂,因为您的搜索表达式相当简单。

我从来没有比较过String搜索函数的性能和RegExp,因为我认为有基于相同的实现。如果String.match()更快,那么您应该尝试 String.search() .使用索引,您可以计算下一次搜索迭代的子字符串。

help.adobe.com 网站上找到了这个,...

"将正则表达式与字符串一起使用的方法:exec() 方法"

。该数组还包括一个索引属性,指示子字符串匹配开始的索引位置...

var pattern:RegExp = /w*shw*/gi; 
var str:String = "She sells seashells by the seashore"; 
var result:Array = pattern.exec(str); 
while (result != null) 
{ 
    trace(result.index, "t", pattern.lastIndex, "t", result); 
result = pattern.exec(str); 
} 
//output:  
// 0      3      She 
// 10      19      seashells 
// 27      35      seashore

最新更新