Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match words in a sentence by its prefix

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

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

What would be the right regex pattern if I want it to match a sentence that has at least a word starting with key prefix? For example:

If I have a sentence

"This is a dog"

when key is 'do', then it should match that sentence since prefix 'do' is a substring of 'dog'.

My solution as of now only works for the first word of the sentence. It so far only matches that sentence if I type in 't' or 'th' or 'this'. It wouldnt match that sentence whenever I type in 'i' (prefix for 'is') or 'do' (prefix for 'dog').

like image 983
Benny Tjia Avatar asked Dec 07 '22 16:12

Benny Tjia


1 Answers

You can use the expression /\bprefix\w+/. This should match any word starting with "prefix". Here the \b represents a word boundary and \w is any word character.

If you don't want to get the whole word, you can just do /\bprefix/. If you want to put this in a string, you also have to escape the \: '\\bprefix'.

like image 169
Tikhon Jelvis Avatar answered Dec 31 '22 18:12

Tikhon Jelvis