Based on this answer
Regular Expressions: Is there an AND operator?
I tried the following on http://regexpal.com/ but was unable to get it to work. What am missing? Does javascript not support it?
Regex: (?=foo)(?=baz)
String: foo,bar,baz
Based on this answer
Regular Expressions: Is there an AND operator?
I tried the following on http://regexpal.com/ but was unable to get it to work. What am missing? Does javascript not support it?
Regex: (?=foo)(?=baz)
String: foo,bar,baz
It is impossible for both (?=foo)
and (?=baz)
to match at the same time. It would require the next character to be both f
and b
simultaneously which is impossible.
Perhaps you want this instead:
(?=.*foo)(?=.*baz)
This says that foo
must appear anywhere and baz
must appear anywhere, not necessarily in that order and possibly overlapping (although overlapping is not possible in this specific case because the letters themselves don't overlap).
我在 javascript 自动完成插件中使用的布尔 (AND) 加通配符搜索示例:
要匹配的字符串:"my word"
要搜索的字符串:"I'm searching for my funny words inside this text"
您需要以下正则表达式:/^(?=.*my)(?=.*word).*$/im
解释:
^在行首断言位置
?=正前瞻
.*匹配任何字符(换行符除外)
()组
$在行尾断言位置
i修饰符:不敏感。不区分大小写的匹配(忽略 [a-zA-Z] 的大小写)
m修饰符:多行。导致 ^ 和 $ 匹配每行的开始/结束(不仅是字符串的开始/结束)
在此处测试正则表达式:https ://regex101.com/r/iS5jJ3/1
因此,您可以创建一个 javascript 函数:
例子:
function fullTextCompare(myWords, toMatch){
//Replace regex reserved characters
myWords=myWords.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
//Split your string at spaces
arrWords = myWords.split(" ");
//Encapsulate your words inside regex groups
arrWords = arrWords.map(function( n ) {
return ["(?=.*"+n+")"];
});
//Create a regex pattern
sRegex = new RegExp("^"+arrWords.join("")+".*$","im");
//Execute the regex match
return(toMatch.match(sRegex)===null?false:true);
}
//Using it:
console.log(
fullTextCompare("my word","I'm searching for my funny words inside this text")
);
//Wildcards:
console.log(
fullTextCompare("y wo","I'm searching for my funny words inside this text")
);
也许你正在寻找这样的东西。如果您想选择同时包含“foo”和“baz”的完整行,则此 RegEx 将遵守:
.*(foo)+.*(baz)+|.*(baz)+.*(foo)+.*
也许只是一个 OR 运算符|
就足以解决您的问题:
细绳:foo,bar,baz
正则表达式:(foo)|(baz)
结果:["foo", "baz"]