Regex to match words in a sentence by its prefix

后端 未结 4 1592
礼貌的吻别
礼貌的吻别 2021-01-19 15:25

I have this regex on mongodb query to match words by prefix:

{sentence: new RegExp(\'^\'+key,\'gi\')}

What would be the right regex pattern

4条回答
  •  萌比男神i
    2021-01-19 16:17

    The other answers suggesting the word boundary matching are neat, but will mean that an index isn't used efficiently. If you need fast lookups, you might want to consider adding a field "words" with each of your words broken up, i.e.

    {sentence: "This is a dog",
      words: ["This", "is", "a", "dog"]}
    

    After putting an index on the words field, you can go back to using:

    {words: new RegExp('^'+key,'gi')}
    

    and a key of "do" will now match this object and use an index.

提交回复
热议问题