编辑以澄清:oneword
是用户可能使用的搜索查询。我需要匹配两者oneword
,one word
或者word one
使用这个正则表达式
如何以任何给定的顺序匹配带有或不带有空格的字符串?
这是我目前的查询/^(?=.*one)(?=.*word).*$/i
积分:http : //www.rubular.com/r/QFEfj9lMn3
所以给定文本oneword one word word one
和搜索查询/^(?=.*one)(?=.*word).*$/i
匹配所有三个,但/^(?=.*oneword).*$/i
只匹配文本的第一部分。
有没有比在每个字母前添加一个可选字符更好的方法来解决这个问题?
谢谢
试试这个简单的正则表达式生成
function showMatches(sampleInput, searchInput) {
console.log(sampleInput, searchInput);
if (sampleInput.length && searchInput.length) {
var regexStr = searchInput.split(" ").join("\\\s*") + "|" + searchInput.split(" ").reverse().join("\\\s*");
var regex = new RegExp(regexStr, "gi");
//console.log(regex);
console.log(sampleInput.match(regex))
}
}
showMatches("one word word one oneword", "one word");
解释
\\\s*
"|"
注- 您可能还想使用此处显示的方法从搜索输入中转义特殊的正则表达式字符。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句