简体   繁体   English

正则表达式匹配句子中的部分单词

[英]Regex match partial words in a sentence

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.用户可能会输入 2 个部分单词,我需要能够匹配与其中一些字符匹配的最近单词,考虑到当输入值包含空格时我需要查看下一个单词。

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.我遇到的问题是,例如,如果我键入 stack 它匹配,如果我键入 overflow 它匹配,如果我键入 stack over 它仍然匹配,但如果第一个单词不完整它不匹配。

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. 

One approach is to prepare your input before creating a RegExp .一种方法是在创建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.为此,只需将输入字符串按空格拆分并与.*?[ ]连接,然后构建正则表达式。 Note the blank character [ ] after it, if you want to keep the spaces between words.如果要保留单词之间的空格,请注意其后的空格字符[ ]

 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))

Building on @testing_22, maybe use prepare with "or" (pipe):在@testing_22 的基础上,可以使用带有“或”(管道)的准备:

 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
------------------

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM