tags:

views:

51

answers:

1

I have a regex that looks like this

((1010xxx)?(\d{11}|\d{10}|\d{7})+)

Basically I want it to match

8085551234
5551234
10102338085551234

and it should fail on
1010233

This is more for validation being done on an xsd than an actual matcher.

PS. I am trying to match US telephone numbers 7 - 11 digits long with an optional 1010xxx at the front. Also if it is 1010xxx it should not pass. xxx is any 3 digits.

+2  A: 

If all you want is to make sure that it's a 7, 10, or 11 digit string, making sure that if it's only 7 digits it doesn't start with '1010', you can use a negative lookahead assertion before your match on \d{7}, i.e.:

((\d{11}|\d{10}|(?!1010)\d{7})+)
Adam Bellaire
Yes, but for some reason 10102334 passes?
arinte
It *contains* a 7-digit string. If you don't want that to match either, you can put start and end anchors at the ends of the regex, e.g. ^((\d{11}|\d{10}|(?!1010)\d{7})+)$
Adam Bellaire
Instead of \d{7}, if you are using the negative look behind, you should use `(?<!1010)\d{3}`
Peter Di Cecco
@Peter, why? What's wrong with the look ahead? Look ahead is over-all better supported by various regex flavors, so I don't see why you'd want to use look behind here.
Bart Kiers
Sorry, I was confused for a moment. You're solution seems correct.
Peter Di Cecco
Peter, if the answer is correct, please mark it as such. And perhaps also "upvote" it.
Bart Kiers