Regex AND operator

Solution 1:

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

Solution 2:

Example of a Boolean (AND) plus Wildcard search, which I'm using inside a javascript Autocomplete plugin:

String to match: "my word"

String to search: "I'm searching for my funny words inside this text"

You need the following regex: /^(?=.*my)(?=.*word).*$/im

Explaining:

^ assert position at start of a line

?= Positive Lookahead

.* matches any character (except newline)

() Groups

$ assert position at end of a line

i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])

m modifier: multi-line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)

Test the Regex here: https://regex101.com/r/iS5jJ3/1

So, you can create a javascript function that:

  1. Replace regex reserved characters to avoid errors
  2. Split your string at spaces
  3. Encapsulate your words inside regex groups
  4. Create a regex pattern
  5. Execute the regex match

Example:

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

Solution 3:

Maybe you are looking for something like this. If you want to select the complete line when it contains both "foo" and "baz" at the same time, this RegEx will comply that:

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

Solution 4:

Maybe just an OR operator | could be enough for your problem:

String: foo,bar,baz

Regex: (foo)|(baz)

Result: ["foo", "baz"]