PostgreSQL - REGEXP_REPLACE Function
Last Updated :
18 Nov, 2024
The PostgreSQL REGEXP_REPLACE()
function is a powerful text manipulation tool, designed to replace specific substrings within a string based on regular expression patterns. This function is highly beneficial for cleaning, reformatting, and transforming textual data by allowing complex pattern matching and replacement functionality.
In this article, we will explain the PostgreSQL REGEXP_REPLACE()
function in-depth, covering its syntax, common use cases, and detailed examples for effective string manipulation in PostgreSQL.
What is the PostgreSQL REGEXP_REPLACE Function?
The REGEXP_REPLACE()
function in PostgreSQL enables us to search and replace parts of string that match a specified POSIX regular expression pattern. This allows for more dynamic and flexible text transformations than traditional replace functions, making it ideal for data cleaning and advanced string manipulation.
Why Use REGEXP_REPLACE() in PostgreSQL?
Using REGEXP_REPLACE()
can save time and simplify tasks when dealing with:
- Data standardization (e.g., transforming name formats)
- Data cleansing (e.g., removing unwanted characters or digits)
- Complex text replacements that depend on dynamic patterns.
Syntax
REGEXP_REPLACE(source, pattern, replacement_string, [, flags])
Key Terms
'source_string'
: This is the original string where the search and replace operation is performed.
'pattern'
: A POSIX regular expression pattern that identifies substrings to be replaced.
'replacement_string'
: The string that replaces substrings matching the pattern.
'flags
(optional)': Controls the behavior of the matching operation. Commonly used flags include 'g' for global replacement and 'i' for case-insensitive matching.
PostgreSQL REGEXP_REPLACE Function Examples
Let us take a look at some of the examples of REGEXP_REPLACE() Function in PostgreSQL to better understand the concept. These examples will show how pattern-based replacements can be used for various data manipulation tasks.
Example 1: Rearranging Name Format
Suppose we have a name formatted as first_name last_name
, and we want to reverse the order to last_name
,
first_name
. The following query demonstrates how to use REGEXP_REPLACE()
to achieve this:
Query:
SELECT REGEXP_REPLACE('Raju Kumar', '(.*) (.*)', '\2, \1');
Output

Explanation:
This query uses the regular expression '(.*) (.*)
'
to capture two groups (first_name
and last_name
). The backreference \2
(for last_name
) and \1
(for first_name
) rearranges the name format.
Example 2: Removing Alphabets from String
Suppose we have data in the form of a string. This string is mixed with alphabets and digits as ABC12345xyz
and we want to remove all alphabetic characters, leaving only the digits. The following query removes all alphabets e.g., A, B, C, etc from the source string:
Query:
SELECT REGEXP_REPLACE('ABC12345xyz', '[[:alpha:]]', '', 'g');
Output

Explanation:
This query uses [[:alpha:]]
to match any alphabetic character (A-Z, a-z). The global flag 'g'
ensures that all alphabetic characters are removed from the string.
Important points about PostgreSQL REGEXP_REPLACE Function
- In
REGEXP_REPLACE()
, you can use backreferences ('\1'
, '\2'
, etc.) in the 'replacement_string'
to refer to groups captured in the pattern.
- Special characters in regular expressions (e.g.,
^
, $
, \
, .
) have specific meanings. Ensure proper escaping of these characters if they are meant to be interpreted literally.
- Use of POSIX character classes ('
[:alpha:]'
, '[:digit:]'
, etc.) and non-greedy matching (.*?
, .+?
) can provide more precise control over pattern matching behavior.
- By default, PostgreSQL regular expressions are case-sensitive.
Conclusion
The REGEXP_REPLACE()
function in PostgreSQL is a highly flexible tool that supports advanced pattern-based replacements, offering greater flexibility than standard replacement functions. By using POSIX regular expressions, backreferences, and flags, REGEXP_REPLACE()
enables complex data transformations with ease, making it an invaluable asset for data cleansing and formatting tasks.
Similar Reads
SQL Tutorial Structured Query Language (SQL) is the standard language used to interact with relational databases. Whether you want to create, delete, update or read data, SQL provides the structure and commands to perform these operations. SQL is widely supported across various database systems like MySQL, Oracl
8 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Normal Forms in DBMS In the world of database management, Normal Forms are important for ensuring that data is structured logically, reducing redundancy, and maintaining data integrity. When working with databases, especially relational databases, it is critical to follow normalization techniques that help to eliminate
7 min read
Window Functions in SQL SQL window functions are essential for advanced data analysis and database management. It is a type of function that allows us to perform calculations across a specific set of rows related to the current row. These calculations happen within a defined window of data and they are particularly useful
6 min read
Top 60 DBMS Interview Questions with Answers for 2025 A Database Management System (DBMS) is the backbone of modern data storage and management. Understanding DBMS concepts is critical for anyone looking to work with databases. Whether you're preparing for your first job in database management or advancing in your career, being well-prepared for a DBMS
15+ min read
SQL Exercises : SQL Practice with Solution for Beginners and Experienced SQL (Structured Query Language) is a powerful and flexible tool for managing and manipulating relational databases. Regardless of our experience level, practising SQL exercises is essential for improving our skills. Regular practice not only enhances our understanding of SQL concepts but also builds
15+ min read
SQL Cheat Sheet ( Basic to Advanced) Creating and managing databases in SQL involves various commands and concepts that handle the structuring, querying, and manipulation of data. In this guide, we will see a comprehensive cheat sheet for essential SQL operations, offering a practical reference for tasks ranging from database creation
15 min read
SQL Views Views in SQL are a type of virtual table that simplifies how users interact with data across one or more tables. Unlike traditional tables, a view in SQL does not store data on disk; instead, it dynamically retrieves data based on a pre-defined query each time itâs accessed. SQL views are particular
7 min read
MySQL Tutorial This MySQL Tutorial is made for both beginners and experienced professionals. Whether you're starting with MYSQL basics or diving into advanced concepts, this free tutorial is the ideal guide to help you learn and understand MYSQL, no matter your skill level. From setting up your database to perform
11 min read
Indexing in Databases - Set 1 Indexing is a crucial technique used in databases to optimize data retrieval operations. It improves query performance by minimizing disk I/O operations, thus reducing the time it takes to locate and access data. Essentially, indexing allows the database management system (DBMS) to locate data more
8 min read