问题描述
我正在尝试为项目构建搜索功能,该项目根据用户搜索输入缩小项目,如果它与针对项目列出的关键字匹配。为此,我将项目关键字保存在 data
属性中,并使用RegExp模式将查询与这些关键字匹配。
I'm trying to build a search feature for a project which narrows down items based on a user search input and if it matches the keywords listed against items. For this, I'm saving the item keywords in a data
attribute and matching the query with these keywords using a RegExp pattern.
我目前正在使用这个表达式,我知道这是不正确的,需要你的帮助:
I'm currently using this expression, which I know is not correct and need your help on that:
new RegExp(' \\b('+ query +')','gi')))
其中查询是 |
输入的查询的分隔值由用户(例如 \\b(肉|面食|晚餐)
)。即使只有一场比赛,这也会给我一个匹配,比如说 - 肉
new RegExp('\\b(' + query + ')', 'gi')))
where query is |
separated values of the query entered by the user (e.g. \\b(meat|pasta|dinner)
). This returns me a match even if there is only 1 match, say for example - meat
只是为了扔一些上下文,这是一个小例子:
Just to throw some context, here's a small example:
如果用户输入:肉意大利面晚餐
它应该列出所有的项目所有列出的3个关键字,即肉
面食
和晚餐
。这些与他们输入的顺序无关。
If a user types: meat pasta dinner
it should list all items which have ALL the 3 keywords listed against them i.e. meat
pasta
and dinner
. These are independent of the order they're typed in.
你能帮助我一个表达式,它将以任何顺序匹配查询中的所有单词吗?
Can you help me with an expression which will match ALL words in a query, in any order?
推荐答案
你可以实现这一预期断言
You can achieve this will lookahead assertions
^(?=.*\bmeat\b)(?=.*\bpasta\b)(?=.*\bdinner\b).+
在Regexr上查看,确保 \ bmeat \ b
在字符串中的某个地方。其他关键字相同,。+
实际上匹配整个字符串,但前提是断言为真。
(?=.*\bmeat\b)
is a positive lookahead assertion, that ensures that \bmeat\b
is somewhere in the string. Same for the other keywords and the .+
is then actually matching the whole string, but only if the assertions are true.
但它也会与晚餐肉Foobar面食相匹配
But it will match also on "dinner meat Foobar pasta"
这篇关于正则表达式以任何顺序匹配查询中的所有单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!