user2343618
user2343618

Reputation: 163

Search for words with specific starts and endings

I asked a pretty detailed question earlier but it got flagged as a duplicate even though it wasn't.

So I will try and explain what I am trying to do as simply as I can. I want to search a text string for words that begin with specific letters such as "mak", "mind" and "mass" (which are in an array) and end with either nothing extra or "e" or "er". That would be in this instance "mak", "make", "maker", "mind", "minde", "minder", "mass", "masse", "masser".

The code I am using only finds the first match for each word in the array, for instance "mak", "mind" and "mass" in the example.

derPro = ['mak','mind', 'mass', ;
for(i = 0; i < derPro.length; i++){
searchTerm = new RegExp(
                    "\\b" + derPro[i] + "\\b|" +
                    "\\b" + derPro[i] + "e\\b|" +
                    "\\b" + derPro[i] + "er\\b,'gi'");
word = testText.match(searchTerm, "gi");

Upvotes: 0

Views: 75

Answers (3)

Ryan
Ryan

Reputation: 14649

This works, i know you asked for a regex, but I thought this would be useful.

var keys = [
  'mak',
  'mind',
  'mass'
];

var test_words = [
  'mak',
  'make',
  'maker',
  'mind',
  'mass'
];

var matches = [];

for(var i = 0; i < keys.length; i++) {
  var key = keys[i];

  for(var ii = 0; ii < test_words.length; ii++) {
    var test_word = test_words[ii];

    if(test_word.substr(0, key.length) == key) {

      if( test_word.substr(-1) == 'e' || test_word.substr(-2) == 'er') {
        matches.push(test_word);

      }
    }
  }
}

console.log(matches);
// [make, maker, minde]

jsfiddle

Upvotes: 0

anubhava
anubhava

Reputation: 785156

This should work:

var derPro = ['mak','mind', 'mass'];

var searchTerm = new RegExp('\\b((?:' + derPro.join('|') + ')(?:er?)?)\\b', "gi");
//=> /\b((?:mak|mind|mass)(?:er?)?)\b/gi

// now match the regex in a while loop
var matches=[]
while (m = searchTerm.exec('mass maker minde')) matches.push(m[1]);

console.log(matches);

//=> ["mass", "maker", "minde"]

Upvotes: 1

Braj
Braj

Reputation: 46841

Get the matched group from index 1.

/(\b(mak|mind|mass)(e|er)?\b)/gi

Online demo

Upvotes: 0

Related Questions