正则表达式AND运算符

use*_*735 47 regex and-operator

基于这个答案

正则表达式:是否有AND运算符?

我在http://regexpal.com/上尝试了以下内容,但无法让它工作.缺少什么?javascript不支持吗?

正则表达式: (?=foo)(?=baz)

串: foo,bar,baz

Mar*_*ers 75

这是不可能的都(?=foo)(?=baz)在同一时间相匹配.这将需要下一个角色同时兼顾f,b这是不可能的.

也许你想要这个:

(?=.*foo)(?=.*baz)
Run Code Online (Sandbox Code Playgroud)

这表示foo必须出现在任何地方并且baz必须出现在任何地方,不一定按照该顺序并且可能重叠(尽管在这种特定情况下不可能重叠).

  • @ghee22:正则表达式工作正常,但使用正则表达式可能不是测试它的最佳方法,因为没有可见的反馈是否匹配成功或失败(它是零宽度匹配).尝试在Javascript控制台中运行它,或者在表达式的末尾添加".*". (2认同)

Mar*_*rim 11

布尔(AND)加通配符搜索的示例,我在javascript自动完成插件中使用它:

要匹配的字符串:"我的话"

要搜索的字符串:"我正在搜索本文中有趣的单词"

你需要以下正则表达式: "my word"

解释:

^断言一行开头的位置

?=积极前瞻

.*匹配任何字符(换行符除外)

()小组

$断言一行的结尾位置

修饰语:不敏感.不区分大小写的匹配(忽略[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")
);
Run Code Online (Sandbox Code Playgroud)
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")
);
Run Code Online (Sandbox Code Playgroud)


pau*_*rio 5

你需要一个OR运算符|:

串: foo,bar,baz

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

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

  • 问题是关于 AND 逻辑的。如果只有一个 _or_ 其他词存在,则带有交替 (`|`) 的 OR 逻辑也将匹配,这不是意图 - _both_ 必须存在。 (2认同)