tags:

views:

42

answers:

4
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

+1  A: 

MySQL doesn't have a regular expression replace function, but if you have a limited number of unwanted characters you could use a series of replace statements, eg.

select replace(replace(replace(telephone, '-', ''), '(', ''), ')', '') from ...
ar
A: 

You can also use a UDF (user defined function) to have a REGEX_REPLACE.

https://launchpad.net/mysql-udf-regexp

Frankie
+1  A: 

Here is a simple MySQL regex that allows certain characters between groupings of numbers.

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

This matches your records but does not format them such that the misc. characters are removed, but you at least can find the records that match the number in question.

You could easily fix the formatting by changing this into an update statement.

JYelton
what if i want any number not just 1-999-999-9999what if it can be any number, the way that you have it, it must be 999
Matt
I assumed you were trying to find all variations of a specific number, altering the query to find whatever number you were looking for. If you are trying to write a query that will return *just* the numbers, and strip out the extra characters, you'll need to do that similar to what ar suggested, by using `replace` or alter the data in code and update the database. `Regexp` only gives you a boolean result whether the pattern was matched or not.
JYelton
+1  A: 

Use:

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

Reference:

OMG Ponies