trying to understand this regex

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
iffo
Forum Commoner
Posts: 37
Joined: Thu Oct 05, 2006 11:56 am

trying to understand this regex

Post by iffo »

Hi I have a question, this regax is being used to validate phone number what are they trying to do here?



$phone_regex = "/(\([2-9]\d{2}\)\s?|[2-9]\d{2}-|[2-9]\d{2})[1-9]\d{2}-?\d{4}/";
nickvd
DevNet Resident
Posts: 1027
Joined: Thu Mar 10, 2005 5:27 pm
Location: Southern Ontario
Contact:

Post by nickvd »

Code: Select all

/
   (  begin grouping
      \( look for a literal bracket
      [2-9] followed by a single number between 2 and 9
      \d{2} followed by two digits (0-9)
      \) followed by a literal bracket
      \s? there may or may not be a space after the bracket
   |                  OR
      [2-9]  a single digit (2-9)
      \d{2} followed by two digits
      -  followed by a hyphen
   |                  OR
      [2-9]  a single digit (2-9)
      \d{2} followed by two digits
   )  end grouping
   
   [1-9] followed by a digit from 1-9
   \d{2} followed by two more digits from 0-9
   -? followed by a hyphen (that may or not be there)
   \d{4} followed by 4 digits (0-9)
/
I whipped that up quickly, so i may have made an error... Upon simple examination it seems that it will catch a few phone numbers (us/canada only), but would fail on 1 (954) 334 3433, (965) 455 4544 (looking for the existance or absence of a hyphen)
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Or a dot/chars (as some prefer: 800.eat.beef).
Post Reply