您好,我有一个JSON数据库,需要在其中将用户输入与关键字进行匹配。除一个特殊情况外,我在此方面已取得成功。基本上,如果用户输入“ icecream”,则应该与关键字或字符串“ ice cream”匹配。
我尝试删除“冰淇淋”中的空白,使其变为“冰淇淋”,但随后取消了很多其他匹配项,例如“冰淇淋圆锥”,后者变成了“冰淇淋”。在这种情况下是否可以使用正则表达式?
var input = new RegExp("icecream", "i");
var keywords = "ice cream, ice cream cone, plastic container lid";
if (keywords.search(input) != -1) {
//do Something
}
如果我要搜索也应该匹配的“塑料盖”而不是“塑料容器盖”,它也应该在“冰淇淋”和“冰淇淋”之间找到匹配项。任何帮助是极大的赞赏。最终,我正在寻找一种能够解决所有情况的解决方案,而不仅仅是“冰淇淋”与“冰淇淋”。
答案 0 :(得分:2)
var input = new RegExp('icecream'.split('').join('(\\s)*').concat('|icecream'), 'i');
var keywords = "ice cream, ice cream cone, plastic container lid";
if (keywords.search(input) != -1) {
//do Something
}
为回答您的问题,我提出了以下方法:
function makeRegEx(input) {
// The regex for an optional whitespace.
let glueRegex = '(\\s)*';
// Transform the string into an array of characters.
let splittedString = input.split('');
// Join the characters together, with the optional whitespace inbetween.
let joinedString = splittedString.join(glueRegex)
// Add the actual input as well, in case it is an exact match.
joinedString += '|' + input;
// Make a new regex made out of the joined string.
// The 'i' indicates that the regex is case insensitive.
return new RegExp(joinedString, 'i');
}
这将创建一个新的RegEx,在每个字符之间放置一个可选的空格。
这意味着使用给定的字符串icecream
,您最终得到的RegEx如下所示:
/i(\s)*c(\s)*e(\s)*c(\s)*r(\s)*e(\s)*a(\s)*m/i
此正则表达式将在以下所有情况下匹配:
整个方法也可以简化为:
let input = new RegExp(input.split('').join('(\\s)*').concat(`|${input}`), 'i');
它很短,但也很不可读。
集成到您的代码中,如下所示:
function makeRegEx(input) {
// The regex for an optional whitespace.
let glueRegex = '(\\s)*';
// Transform the string into an array of characters.
let splittedString = input.split('');
// Join the characters together, with the optional whitespace inbetween.
let joinedString = splittedString.join(glueRegex)
// Add the actual input as well, in case it is an exact match.
joinedString += '|' + input;
// Make a new regex made out of the joined string.
// The 'i' indicates that the regex is case insensitive.
return new RegExp(joinedString, 'i');
}
let userInput = 'icecream';
let keywords = "ice cream, ice cream cone, plastic container lid";
let input = makeRegEx('icecream');
// Check if any of the keywords match our search.
if (keywords.search(input) > -1) {
console.log('We found the search in the given keywords on index', keywords.search(input));
} else {
console.log('We did not find that search in the given keywords...');
}
或者这个:
var input = new RegExp('icecream'.split('').join('(\\s)*').concat('|icecream'), 'i');
var keywords = "ice cream, ice cream cone, plastic container lid";
if (keywords.search(input) != -1) {
//do Something
}
答案 1 :(得分:1)
您需要搜索才能成为正则表达式吗?如果仅搜索关键字就足够了,则可以使用indexOf并首先删除空格
var input = 'icecream';
var keywords = "ice cream, ice cream cone, plastic container lid";
if (keywords.replace(/\s/g, '').toLowerCase().indexOf(input) != -1) { alert('success!'); }
编辑:修改以启用不同的搜索
var searches = ['icecream', 'cashcow', 'takeout', 'otherthing']; // array with your searches
var keywords = "ice cream, ice cream cone, plastic container lid"; // input by the user
var tmpKeywords = keywords.replace(/\s/g, '').toLowerCase(); // remove spaces and convert to all lower case
var length = searches.length;
for (var i=0; i<length; i++) { // loop through all the seach words
if (tmpKeywords.indexOf(searches[i]) != -1) {
console.log(searches[i] + ' exists in the input!');
}
}
答案 2 :(得分:1)
您可以这样做:
let iceexpression=/ice\s*cream/g
let input="testinput icecream";
if(input.search(iceexpression)){
console.log("found");
}
答案 3 :(得分:0)
您可以使用通配符,例如/ice *cream/g
您可以尝试使用正则表达式here并阅读不同的输入内容here
这是一个更新的示例,可以处理任何输入
var keywords = "ice cream, ice cream cone, ice cream c, plastic container lid";
function search()
{
var textToFind = document.getElementById("searchInput").value;
var input = new RegExp(textToFind.toString() + "*", "i");
var words = keywords.split(",");
words.forEach(function(word) {
if(word.match(input))
{
console.log(word);
}
});
}
<input id="searchInput"\>
<button id="search" onclick="search()">search</button>
答案 4 :(得分:0)
在以下解决方案中,我不使用regexp,而是根据上一个列表的两个单词(在逗号之间)的组合生成新的关键字列表。
var input1 = "ice cream"
var input2 = "icecream"
var input3 = "plastic lid"
var keywords = "ice cream, ice cream cone, plastic container lid";
let merge = a => {
let result=[a.join(' ')];
a.forEach((x,i)=>{
for(let j=i+1; j<a.length; j++) result.push(x+a[j])
for(let j=i+1; j<a.length; j++) result.push(x+' '+a[j])
});
return result;
}
let moreKeywords = keywords.split(', ').map( k=> merge(k.split(' ')) ).flat();
if(moreKeywords.includes(input1)) console.log('contains',input1);
if(moreKeywords.includes(input2)) console.log('contains',input2);
if(moreKeywords.includes(input3)) console.log('contains',input3);
console.log('moreKeywords:', moreKeywords);