Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make regex match only first occurrence of each match?

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

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.

like image 248
userBG Avatar asked Apr 13 '12 15:04

userBG


2 Answers

Remove g flag from your regex:

/\b(keyword|whatever)\b/i
like image 112
antyrat Avatar answered Oct 05 '22 02:10

antyrat


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.

Example:

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
}
like image 24
Randy the Dev Avatar answered Oct 05 '22 03:10

Randy the Dev