Skip to main content
Documents
Clauses StatementsKeywordsExpressionsFunctionsIndexesPerformance Optimization

MySQL REGEXP_REPLACE Expressions

The `REGEXP_REPLACE` function in MySQL allows you to search for a regular expression pattern in a string and replace it with a specified replacement string. It is useful for performing text manipulation and data cleaning tasks.

Usage

The `REGEXP_REPLACE` function is used when you need to find and replace text patterns in strings using regular expressions. This function is particularly helpful for complex substitutions that go beyond simple string replacements. Available from MySQL 8.0.4 onwards, ensure your version supports this function before use.

REGEXP_REPLACE(expression, pattern, replacement [, flags])
  • expression: The string to search within.
  • pattern: The regular expression pattern to search for.
  • replacement: The string to replace the matched pattern.
  • flags: Optional flags to modify the behavior, such as case sensitivity.

Examples

1. Basic Replacement

SELECT REGEXP_REPLACE('hello world', 'world', 'universe');

This example replaces the word "world" with "universe" in the given string, resulting in "hello universe".

2. Case Insensitive Replacement

SELECT REGEXP_REPLACE('Hello World', 'world', 'universe', 'i');

Using the 'i' flag, this example performs a case-insensitive replacement, transforming "Hello World" into "Hello universe".

3. Complex Pattern Replacement

SELECT REGEXP_REPLACE('abc123def456', '[0-9]+', '#');

Here, any sequence of digits is replaced with a hash symbol, changing "abc123def456" to "abc#def#".

4. Replacement with Multiple Flags

SELECT REGEXP_REPLACE('Hello\nWorld', '^world$', 'universe', 'mi');

This example uses both the 'm' and 'i' flags for a multi-line, case-insensitive search and replace. It transforms "Hello\nWorld" to "Hello\nuniverse".

Tips and Best Practices

  • Use specific patterns. Define precise regular expressions to avoid unintended replacements.
  • Test patterns separately. Before using them in `REGEXP_REPLACE`, ensure your regular expressions match expected patterns. Testing with small data samples can help prevent unintended data manipulation.
  • Leverage flags wisely. Use flags such as 'i' for case-insensitive searches or 'm' for multi-line mode to refine your replacements.
  • Consider performance. Regular expressions can be computationally expensive, so use them judiciously, especially on large datasets.
  • Be aware of character encodings. Ensure that your character encoding settings are compatible with your regular expressions to avoid unexpected results.

SQL Upskilling for Beginners

Gain the SQL skills to interact with and query your data.
Start Learning for Free