如何使用 string.match 方法查找字符串中同一单词的多次出现?
在 Actionscript 和 Adobe Flex 中,我将模式和正则表达式(带有全局标志)与 string.match 方法一起使用,它按照我想要的方式工作,除非匹配返回文本中同一单词的多次出现。在这种情况下,该单词的所有匹配项仅指向该单词第一次出现的索引。例如,如果文本是“catdogcatcatcow”并且模式是搜索cat*,则match方法将返回一个包含三个“cat”出现的数组,但是,它们都仅指向第一个出现的索引当我在数组循环中使用 indexOf 时,会出现 cat 。我假设这就是 string.match 方法的方式(尽管如果我做错了什么或遗漏了什么,请告诉我!)。我想找到每个匹配项的具体索引,即使它是先前已经匹配过的单词。
我想知道 string.match 方法是否就是这样,如果是的话,是否有人知道最好的方法是什么。谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题不在于
match
方法,而是在于indexOf
方法您必须使用适当的
startIndex
调用indexOf
- 换句话说,您必须从上一场比赛的末尾开始搜索。您还可以使用
regex.exec 执行此操作
方法:The problem is not with the
match
method, it is with theindexOf
methodYou have to call
indexOf
with appropriatestartIndex
- in other words, you've to start searching from the end of previous match.You can also do this using
regex.exec
method: