本文介绍了如何使用string.match方法查找多次出现同一个词在一个字符串的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ActionScript和Adobe Flex的,我使用的模式和正则表达式(与全球标志)与string.match方法和它的作品我怎么样,除非比赛返回多次出现的同一个词在文本。在这种情况下,所有的该单词的匹配仅指向该索引用于该字的第一次出现。例如,如果文本是猫的狗猫猫牛人的模式是搜索猫*,比赛方法返回的三宗猫的数组,但是,它们都指向第一只指数出现的猫当我使用的indexOf在遍历数组。我假设这是多么的string.match方法是(但请让我知道,如果我做错事,或缺少的东西!)。我想找到一个匹配每次出现的具体指标,哪怕是一个词,已经是previously匹配的。

我想如果这是多么的string.match方法是,如果是这样,如果任何人有任何想法什么是最好的方式做,这将是。谢谢你。

解决方案

现在的问题是不是与匹配的方法,它是用的

 函数的indexOf(VAL:字符串,在startIndex:数= 0):INT
 

您必须调用的indexOf 适当的startIndex - 换句话说,你已经开始从搜索的previous比赛结束。

 变种S:字符串=猫的狗猫猫牛猫;
VAR匹配:数组= s.match(/猫/ G?);
迹(matches.join()); // [猫,猫,猫,猫]
VAR K:数= 0;
对于(VAR我:数量= 0; I< matches.length;我++)
{
    K = s.indexOf(火柴〔Ⅰ〕中,k);
    跟踪(比赛#+ I +是+ K);
    K + =匹配[I] .length;
}
 

您也可以使用做到这一点 regex.exec 方式:

 变种S:字符串=猫的狗猫猫牛猫;
变种R:?正则表达式= /猫/克;
VAR匹配:对象;
而((匹配= r.exec(S))!= NULL)
{
  跟踪(比赛在+ match.index +\ N+
    匹配的子字符串为+比赛[0]);
}
 

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 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

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]);
}

这篇关于如何使用string.match方法查找多次出现同一个词在一个字符串的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 10:29