0

How can I use regular expressions in MySQL to rewrite the column value to be matched with an exact string? I can only find guides that do the opposite.

SELECT * FROM customers WHERE regexp_replace('([^0-9])', '', phone) = '0123456789';

The reason is that the column can contain all kinds of formatting e.g. "012-345 6789" "(0)12-3456789" and so on...

Please note: This is NOT a question about how data should better be stored. But wheither regexp replaces are possible or not. The example is only demonstrative to simplify the question and it's nature.

6
  • 2
    Shouldn't this check be applied while entering values in database ? That would save the pain of checking it while retrieving. Commented Mar 6, 2016 at 13:44
  • 1
    Don't use the database to store formatted values. Formatting should be done by functions upon retrieval, either in MySql or PHP. Commented Mar 6, 2016 at 13:49
  • In the MySQL documentation I found this: "The REPLACE function does not support regular expression so if you need to replace a text string by a pattern you need to use MySQL user-defined function (UDF) from external library, check it out here MySQL UDF with Regex." Commented Mar 6, 2016 at 13:59
  • Thank you for all your feedback that a better shot is to keep the input data to database in a consistent format. I would like the thread to focus on whither or not there is a regexp_replace possibility in MySQL regardless of the actual cases or examples. Commented Mar 6, 2016 at 14:04
  • What version are you using? Only MariaDB has regexp_replace(). Commented Mar 7, 2016 at 2:47

1 Answer 1

2

You can improve your application using this 2 steps:

  • write migration which convert you data with different formats to one canonical
  • move formatting of this values to your view layer

This approach gives you:

  • ease in searching by this field
  • flexibility in using different formats for this field in differents views
Sign up to request clarification or add additional context in comments.

Comments

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.