How to use the string.match method to find multiple occurrences of the same word in a string?
In Actionscript and Adobe Flex, I'm using a pattern and regexp (with the global flag) with the string.match method and it works how I'd like except when the match returns multiple occurrences of the same word in the text. In that case, all the matches for that word point only to the index for the first occurrence of that word. For example, if the text is "cat dog cat cat cow" and the pattern is a search for cat*, the match method returns an array of three occurrences of "cat", however, they all point to only the index of the first occurrence of cat when i use indexOf on a loop through the array. I'm assuming this is just how the string.match method is (although please let me know if i'm doing something wrong or missing something!). I want to find the开发者_C百科 specific indices of every occurrence of a match, even if it is of a word that was already previously matched.
I'm wondering if that is just how the string.match method is and if so, if anyone has any idea what the best way to do this would be. Thanks.
The problem is not with the match
method, it is with the indexOf
method
function indexOf(val:String, startIndex:Number = 0):int
Searches the string and returns the position of the first occurrence of
val
found at or afterstartIndex
within the calling string.
You have to call indexOf
with appropriate startIndex
- in other words, you've to start searching from the end of previous match.
var s:String = "cats dog cat cats cow cat";
var matches:Array = s.match(/cats?/g);
trace(matches.join());// ["cats", "cat", "cats", "cat"]
var k:Number = 0;
for(var i:Number = 0; i < matches.length; i++)
{
k = s.indexOf(matches[i], k);
trace("match #" + i + " is at " + k);
k += matches[i].length;
}
You can also do this using regex.exec
method:
var s:String = "cats dog cat cats cow cat";
var r:RegExp = /cats?/g;
var match:Object;
while((match = r.exec(s)) != null)
{
trace("Match at " + match.index + "\n" +
"Matched substring is " + match[0]);
}
精彩评论