0

I have a list of coma separated words like cooler,bestwishes,congrat. I want to use regex to find the best matching word in this list. e.g Congratulations or Congrats matches congrat in the above list.

I have tried the regex below but it only works if the word in regex is the subset.

const regex = /[^,]*congratulation[^,]*/g;
const str = `this,cart,open,best-wishes,congrat`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

Is this possible using regex ?

Saadi
  • 1,292
  • 13
  • 22
  • Can you give a list of words to match? – Akshay Bande Nov 08 '19 at 05:03
  • The list of words are: cool,bestwishes,congrat,greatjob,welldone,kudos,thumbsup,keeprocking. The regex will have one word that will be matched with the above. so lets say if the regex contains keeprockingbuddy, it should match keeprocking – Saadi Nov 08 '19 at 05:05
  • What is the problem, with what you have implemented? – Akshay Bande Nov 08 '19 at 05:12
  • the regex **/[^,]*congratulation[^,]*/gi** is not returning **congrat** – Saadi Nov 08 '19 at 05:14
  • 1
    Regex is good for exact comparisons, not that much for approximate ones. Use fuzzy matchers, like in this potential duplicate: [Javascript fuzzy search that makes sense](https://stackoverflow.com/questions/23305000/javascript-fuzzy-search-that-makes-sense), – Amadan Nov 08 '19 at 05:41
  • I think i will have to follow **Akshay-bande's** answer for time. but i will surely give the fuzzy search a try later when i get time. – Saadi Nov 08 '19 at 06:10

1 Answers1

1

Instead of searching for the target word's substring in a list of words you can search list of words in target word. That will reduce complexity and make it easier.

let words = ["cool","bestwishes","congrat","greatjob","welldone","kudos","thumbsup","keeprocking","rock","congrats"];
let word = "keeprockingbuddy";
let match = getMatchingWords(words,word);
console.log(match); // ["keeprocking", "rock"]
match = getMatchingWords(words,"Congratulations"); 
console.log(match); // ["congrat"]


function getMatchingWords(words,target){
  let ans = [];
  words.forEach((w)=>{
    let found = target.match(new RegExp(w,"i"));
    if(found){
      ans.push(w);
    }
  })
  ans = ans.length ? ans:"not found";
  return ans;
}

Hope it answers your question.

Akshay Bande
  • 2,491
  • 2
  • 12
  • 29