Home > database >  Regex match partial words in a sentence
Regex match partial words in a sentence

Time:04-08

I have an input that can receive any string value. The user might type 2 partial words and I need to be able to match the nearest word that matches some of those characters taking into account that when the input value contains a space I need to look in the next word.

The problem that I am having is that for example if I type stack it matches, if I type overflow it matches, if I type stack over it still matches, but if the first word is not complete it does not match.

An example to clarify:

const mySentence = "stack overflow";
let myInput = "sta over"; //input from user

let reg = new RegExp(myInput, 'i');

mySentence.match(reg); //this needs to match mySentence. 

CodePudding user response:

One approach is to prepare your input before creating a RegExp. Since you want to get partial words in the sentence, use the lazy version of the dot star (.*?) to match any possible characters existing before each space.

To do that, simply split the input string by the space and concat with .*? and then construct the regular expression.

const mySentence = "stack overflow bad but stackoverflow cool";
let myInput = "sta over ba b st coo"; //input from user

let reg = new RegExp(myInput.split(" ").join(".*?"), 'i');

console.log(mySentence.match(reg))

CodePudding user response:

Building on @testing_22, maybe use prepare with "or" (pipe):

    const mySentence = "stack overflow";
    let myInput = "sta over ba b st coo"; //input from user
    
    var cases = [
        "sta over",
        "stack",
        "overflow",
        "stack over",
        "bob"
    ];
    
    cases.forEach(item => {
        let reg = new RegExp(item.split(" ").join("|"), 'gi');
        console.log("------------------")
        console.log("case: "   item)
        console.log(mySentence.match(reg))
    });

results:

------------------
case: sta over
[
    "sta",
    "over"
]
------------------
case: stack
[
    "stack"
]
------------------
case: overflow
[
    "overflow"
]
------------------
case: stack over
[
    "stack",
    "over"
]
------------------
case: bob
null
------------------
  • Related