Rushino
Rushino

Reputation: 9485

AND operator in regex doesn't work

I wish to be able to match those values.

  1. not 0 8 times
  2. not 0 11 times

AND

  1. 0-9 8 times
  2. 0-9 11 times

It seem there is no AND operators i tried this..

^(?=[0-9]{8}|[0-9]{11})(?=[^0]{8}|[^0]{11})$

But it doesn't seem to work at all. Any ideas ?

Upvotes: 0

Views: 84

Answers (3)

The Guy with The Hat
The Guy with The Hat

Reputation: 11132

This regex should work:

^(?!0{8}$)(?!0{11}$)(?:\d{8}|\d{11})$

Online explanation and demonstration: http://regex101.com/r/sH1nZ5

Alternatively, you could use

^(?!0{8}$)(?!0{11}$)\d{8}(?:\d{3})?$

which does the exact same thing: http://regex101.com/r/iX2xM2

Upvotes: 1

user557597
user557597

Reputation:

Or, it could be written this way

 # ^(?=.{8}(?:.{3})?$)[1-9]+$

 ^ 
 (?=
      .{8} 
      (?: .{3} )?
      $ 
 )
 [1-9]+ 
 $ 

Upvotes: 0

Michael Tang
Michael Tang

Reputation: 4896

You might be looking for the union of two sets and the OR | operator if you want to match both sets.

^(?=[0-9]{8}|[0-9]{11})|(?=[^0]{8}|[^0]{11})$

If you simply want to match a string that is not 0 8 or 11 times, followed by 0-9 8 or 11 times, just put them in order.

Upvotes: 1

Related Questions