Benny Tjia
Benny Tjia

Reputation: 4883

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

Upvotes: 6

Views: 20462

Answers (4)

Nic Cottrell
Nic Cottrell

Reputation: 9685

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.

Upvotes: 2

Tikhon Jelvis
Tikhon Jelvis

Reputation: 68152

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

Upvotes: 8

nnnnnn
nnnnnn

Reputation: 150080

^ 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

Upvotes: 1

wutz
wutz

Reputation: 3274

Use the \b anchor to match word boundaries:

\bdo

finds 'do' in 'nice dog', but doesn't match 'much ado about nothing'.

Upvotes: 7

Related Questions