如何使正则表达式只匹配每个匹配的第一次出现? [英] How to make regex match only first occurrence of each match?

查看:689
本文介绍了如何使正则表达式只匹配每个匹配的第一次出现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

/\b(keyword|whatever)\b/gi

如何修改上面的javascript正则表达式以仅匹配每个单词的第一次出现(我相信这称为非贪婪)?

How can I modify the above javascript regex to match only the first occurance of each word (I believe this is called non-greedy)?

首次出现关键词和第一次出现无论什么,我可能会在那里放更多的词。

First occurance of "keyword" and first occurance of "whatever" and I may put more more words in there.

推荐答案

你是什么用单一的正则表达式完成无法实现的目标。相反,你必须存储你想要在数组中找到的每个单词,遍历所有单词以搜索答案,然后对于任何匹配,将结果存储在数组中。

What you're doing is simply unachievable with a singular regular expression. Instead you will have to store every word you wish to find in an array, loop through them all searching for an answer, and then for any matches, store the result in an array.

示例:

var words = ["keyword","whatever"];
var text = "Whatever, keywords are like so, whatever... Unrelated, I now know " +
           "what it's like to be a tweenage girl. Go Edward.";
var matches = []; // An empty array to store results in.
/* When you search the text you need to convert it to lower case to make it
   searchable.
 * We'll be using the built in method 'String.indexOf(needle)' to match 
   the strings as it avoids the need to escape the input for regular expression
   metacharacters. */

//Text converted to lower case to allow case insensitive searchable.
var lowerCaseText = text.toLowerCase();
for (var i=0;i<words.length;i++) { //Loop through the `words` array
    //indexOf returns -1 if no match is found
    if (lowerCaseText.indexOf(words[i]) != -1) 
        matches.push(words[i]);    //Add to the `matches` array
}

这篇关于如何使正则表达式只匹配每个匹配的第一次出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆