65

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

4

4 回答 4

100

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).

于 2010-06-14T22:15:30.963 回答
21

我在 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 函数:

  1. 替换正则表达式保留字符以避免错误
  2. 在空格处拆分字符串
  3. 将您的话封装在正则表达式组中
  4. 创建正则表达式模式
  5. 执行正则表达式匹配

例子:

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")
);

于 2016-06-08T03:04:24.720 回答
1

也许你正在寻找这样的东西。如果您想选择同时包含“foo”和“baz”的完整行,则此 RegEx 将遵守:

.*(foo)+.*(baz)+|.*(baz)+.*(foo)+.*

于 2016-04-05T11:27:00.473 回答
1

也许只是一个 OR 运算符|就足以解决您的问题:

细绳:foo,bar,baz

正则表达式:(foo)|(baz)

结果:["foo", "baz"]

于 2016-02-24T15:28:29.340 回答