Evan Levesque
Evan Levesque

Reputation: 3203

How to combine two regex conditions?

I am trying to write a regular expression in JavaScript that ANDs two conditions A and B

(A)(B) is obviously not a valid solution.

My two regex are:

^((?=.*?(.*([\.]).*)[^@])[^@]+)$

^((?!\.\.).)*$


so ^((?=.*?(.*([\.]).*)[^@])[^@]+)(((?!\.\.).)*)$ does not AND the two regexes

How can I do that ? is there a general rule ?

Upvotes: 1

Views: 4015

Answers (3)

Pranav C Balan
Pranav C Balan

Reputation: 115222

You can combine them like as follows

^(?=.*?(.*([\.]).*)[^@])((?!\.\.)[^@])+$

Regex explanation here.

Regular expression visualization

Upvotes: 1

Alan Moore
Alan Moore

Reputation: 75222

Try breaking it down to the actual conditions you're testing for; I see three of them:

  • contains at least one dot (.)
  • doesn't contain a double dot (..)
  • one or more of any characters except @

Convert two of them to lookaheads, then chain all three together into one regex. That would be:

^(?=.*\.)(?!.*\.\.)[^@]+$

But maybe you want to be sure it doesn't start or end with a dot. That's easier to do without lookaheads:

^[^@.]+(?:\.[^@.]+)+$

Upvotes: 1

Sam
Sam

Reputation: 20486

Sometimes, there isn't an obvious way to combine to expressions. Like you said, (A)(B) is not valid. Since regular expressions aren't a programming language, the "obvious" way to do what you're looking for is:

var doesMatch = string.match(/(A)/) && string.match(/(B)/);

Without taking the time to really decipher what you're trying to match, it's hard to say if there is a non-obvious way to combine the two expressions...all I can say is there isn't a generic rule to combine them.

Also, combining two regular expression doesn't necessarily mean it's faster. Take the string foo bar and the expressions ^foo and bar$. The "obvious" combination of those two expressions is ^foo.*?bar$; however, ^foo and bar$ each take 5 steps while the combined version takes 11 steps.

Upvotes: 3

Related Questions