假设我有这样的查询:“一二三”,如果我用|替换空格(管道符)如果字符串包含一个或多个单词,我可以匹配它。这就像逻辑OR。
是否存在类似逻辑AND的东西。只要所有单词都出现在字符串中,它就应该匹配,无论单词排序如何。
不幸的是,我离开了我的Mastering Regular Expressions书:(
编辑:我正在使用Javascript,查询可以包含任意数量的字词。
答案 0 :(得分:6)
尝试前瞻断言:
(?=.*one)(?=.*two)(?=.*three)
但如果你使用三个单独的正则表达式或更简单的字符串搜索操作会更好。
答案 1 :(得分:2)
没有什么比这更好的了。您可以很容易地匹配任何相关单词的三次出现:
(?:\b(?:one|two|three)\b.*){3}
但这与“一二一”匹配就像“一二三”一样容易。
你可以使用像Gumbo描述的超前断言。或者你可以写出排列,如下:
(?\bone\b.*\btwo\b.*\bthree\b|\btwo\b.*\bone\b.*\bthree\b|\bone\b.*\bthree\b.*\btwo\b|\bthree\b.*\bone\b.*\btwo\b|\bthree\b.*\btwo\b.*\bone\b|\btwo\b.*\bthree\b.*\bone\b)
这显然很可怕。
长话短说,做三场独立比赛要好得多。
答案 2 :(得分:2)
在一个中执行此操作的唯一原因是,如果您需要它以特定顺序查找它们。
答案 3 :(得分:0)
如果它需要包含至少列表中的一个词
,请使用此选项 let string='One red, two green and 4 orange';
var words='one two three';
words=words.split(' ').join('|');
let pattern=new RegExp(`(?=(.)*?\\b(${words})\\b)((.)+)`,'g');
if(string.match(pattern)!==null){
//string matches at least one of the words
}else{
//string does not match any of the words
}
如果需要包含列表中的所有字词,请使用此选项
let string='One red, two green and 4 orange';
var words='one two three';
words=words.split(' ').map(function(value,index){return '(?=(.)*?\\b('+value+')\\b)'; }).join('');
let pattern=new RegExp(`${words}((.)+)`,'g');
if(string.match(pattern)!==null){
//string matches all words
}else{
//string does not match all words
}
它有什么作用?首先,它将字符串更改为数组,并以最终形式连接正则表达式,然后使用 Javascript 正则表达式变量插入的魔力。
即使单词列表动态变化,这也将帮助您委托此方法。
*如果您想测试或调整它,您可以在这里进行:doregex.com
*请注意,您不能用任何其他类型的引号(简单的 ' 或双引号)替换反引号 ( ` ),否则表达式将失败。