Regex to match words in a sentence by its prefix

后端 未结 4 1611
礼貌的吻别
礼貌的吻别 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条回答
  •  醉酒成梦
    2021-01-19 16:25

    ^ 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

提交回复
热议问题