正则表达式通过其前缀匹配句子中的单词 [英] Regex to match words in a sentence by its prefix
问题描述
我在mongodb查询上有这个正则表达式,用于按前缀匹配单词:
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:
如果我有一句话
这是一只狗
"This is a dog"
当 key
为'do'时,它应匹配该句话因为前缀'do'是'dog'的子字符串。
when key
is 'do', then it should match that sentence since prefix 'do' is a substring of 'dog'.
我现在的解决方案仅适用于句子的第一个单词。如果我键入't'或'th'或'this',它到目前为止只匹配该句子。每当我输入'i'('is'的前缀)或'do'('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').
推荐答案
使用 \b
锚点以匹配字词边界:
Use the \b
anchor to match word boundaries:
\bdo
在'好狗'中找到'do',但不匹配'ad ad about about没什么'。
finds 'do' in 'nice dog', but doesn't match 'much ado about nothing'.
这篇关于正则表达式通过其前缀匹配句子中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!