I have this regex on mongodb query to match words by prefix:
{sentence: new RegExp(\'^\'+key,\'gi\')}
What would be the right regex pattern
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'
.
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.
Use the \b anchor to match word boundaries:
\bdo
finds 'do' in 'nice dog', but doesn't match 'much ado about nothing'.
^
matches beginning of the string (or beginning of a line if the multiline flag is set).
\b
matches a word boundary.
\bdo
matches words beginning with "do".
So for your example:
{sentence: new RegExp('\\b'+key,'gi')}
(Noting that in a JavaScript string you have to escape backslashes.)
If you will be needing to capture the match(es) to find out what word(s) matched the pattern you'll want to wrap the expression in parentheses and add a bit to match the rest of the word:
new RegExp('(\\b' + key + '\\w*)','gi')
Where \w
is any word character and the *
is zero or more. If you want words that have at least one character more than the key
then use +
instead of *
.
See the many regex guides on the web for more details, e.g., https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions