-2

I am trying to create a regex that only accepts 2 types of phone number inputs. The phone number inputs are (5554446666) and (+15554446666) and nothing else, so this is the regex I wrote:

Regex phoneNumberPattern = new Regex(@"^\s*(?:\+?(\d{1,3}))?(\d{7})");

The problem is when I entered just seven digits (4446666), it accepted it.

Cœur
  • 37,241
  • 25
  • 195
  • 267
nahaelem
  • 133
  • 2
  • 4
  • 13
  • possible duplicate of [C# Regex Phone Number Check](http://stackoverflow.com/questions/8596088/c-sharp-regex-phone-number-check) – MethodMan Mar 12 '15 at 14:51
  • possible duplicate of a million different regex questions. Did you try doing a [search](http://www.regexlib.net/Search.aspx?k=phone)? – Chase Florell Mar 12 '15 at 14:52

2 Answers2

1

Don't make the + conditional - the whole prefix group is conditional, that's how it's supposed to be. Making the + conditional means you're now supporting all phone numbers with 7-10 numbers. Oh, and put $ on the end.

Luaan
  • 62,244
  • 7
  • 97
  • 116
1

Something like this should return the required phone numbers:

(\+1\d{10})|(\d{10})
Eduardo Ramos
  • 416
  • 3
  • 8