字符串中的短语搜索,使正则表达式正确 [英] Phrase search in string, making correct RegExp

查看:23
本文介绍了字符串中的短语搜索,使正则表达式正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会直接开始,这是我所拥有的:

I will start straight, here's what I have:

var SResults = [];
function ActivateSearch(s) {
    SResults = [];

    for (var key in Products){
        if ((' '+Products[key]['n']).search(new RegExp('\\b(('+s+')|('+s+')[s])\\b', 'gi')) > 0) {
            SResults.push(key);
        }
    }
}
ActivateSearch('trampoline cover');

使用此功能,我尝试在 Products[key]['n'] 中查找单词或短语,这是某种标题 ex.蹦床防雨罩 6 英尺长,外加额外设施".

With this function I try to find word or phrases in Products[key]['n'], which is some kind of title ex. "Trampoline rain cover 6ft lenght plus extras".

现在它有了非常基本的工作原理,即在提到的标题中查找搜索词组的每个单词.

Now it has very basic working principle of looking for every single word of search phrase in mentioned title.

问题:

如果有标题蹦床雨罩,并且搜索词是:蹦床罩 - 没有匹配项.

If there is title trampoline rain cover, and search term is: trampoline cover - no matches.

问题:

如何更改正则表达式以匹配上述结果?

How to change regex to match result described above?

推荐答案

另一种选择是 split 并使用具有正向前瞻和字边界的交替,例如:

Another option would have been to split and use alternation with positive lookaheads and word boundaries, such as:

^((?=.*\btrampoline\b)|(?=.*\bcover\b)).*$ 

const regex = /^((?=.*\btrampoline\b)|(?=.*\bcover\b)).*$/gmi;
const str = `Trampoline rain cover 6ft lenght plus extras
Rain cover 6ft lenght plus extras
Trampoline rain 6ft lenght plus extras
Cover trampoline rain 6ft lenght plus extras
Covers trampolines rains 6ft lenght plus extras
`;
let m;

while ((m = regex.exec(str)) !== null) {
	m.forEach((match, groupIndex) => {
		if (groupIndex == 0)
			console.log(`Found match, group ${groupIndex}: ${match}`);
	});
}

如果你想探索/简化/修改表达式,它已经在右上角的面板上解释regex101.com.如果你愿意,你也可以在这个链接,它将如何匹配针对一些样本输入.

If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.

这篇关于字符串中的短语搜索,使正则表达式正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆