Reputation: 3203
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
Reputation: 115222
You can combine them like as follows
^(?=.*?(.*([\.]).*)[^@])((?!\.\.)[^@])+$
Upvotes: 1
Reputation: 75222
Try breaking it down to the actual conditions you're testing for; I see three of them:
.
)..
)@
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
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