43
SELECT telephone_number
FROM table
WHERE telephone_number REGEXP '^1[() -]*999[() -]*999[() -]*9999$';

how do i make so its valid for any number format and any number like

407-888-0909
1(408)998-7654
7776654433
876-7788

right now its only valid for 1-999-999-9999

4
  • What do you mean by "any number format"? Do you mean any string that contains at least one digit? Commented Aug 10, 2010 at 19:18
  • yes but without the "()-" and the spaces Commented Aug 10, 2010 at 19:22
  • 2
    possible duplicate of MySQL regex at runtime Commented Aug 10, 2010 at 19:24
  • 1
    If speed is at all important, you should clean the data in the database and avoid using a regex. :-) Commented Aug 10, 2010 at 19:34

3 Answers 3

64

Use:

SELECT telephone_number
  FROM table
 WHERE telephone_number REGEXP '^1[() -]*[[:digit:]]{3}[() -]*[[:digit:]]{3}[() -]*[[:digit:]]{4}$';

Reference:

Sign up to request clarification or add additional context in comments.

2 Comments

what if i have a value 6309991234 but in the database its in (630)9991234 can i add a REGEXP '^1[() -]*[[:digit:]]{3}[() -]*[[:digit:]]{3}[() -]*[[:digit:]]{4}$'="6309991234"
@John: The brackets support "m,n", so you could use {3,7} to capture "9991234". I'm still messing with the functionality to get optional character support working...
1
SELECT telephone_number
  FROM table
 WHERE telephone_number REGEXP '[1]?[(]?[[:DIGIT:]]{3}[)]?[-]?[[:DIGIT:]]{3}[-]?[[:DIGIT:]]{4}'

Comments

0

It isn't very wise to store phone numbers in a database with spaces, dashes, parentheses, etc. The most efficient way is to truncate all that garbage to a simple 10 digit number. That way you can actually store the number in an INTEGER based column instead of a VARCHAR.

3 Comments

I am not doing the insert so i just need to pull out
This can also be problematic when you need to store a leading 0 for the exchange. Not that he leads to that requirement above.
Use VARCHAR but sanitize it before insertion (e.g. get rid of spaces/dashes/...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.