How to Use regexp_like in PostgreSQL?
Last Updated :
15 Oct, 2024
PostgreSQL database is known for its powerful processing capabilities and one such feature is the ability to use regular expressions (RegEx) to search, filter, and validate data. RegEx allows developers to search for specific patterns in strings, making it useful for the validation of data manipulation of strings and filtering out data.
The regexp_like() utilizes the functionality of regex in PostgreSQL. This article will provide an in-depth understanding of how to use the regexp_like
()
function in PostgreSQL, including its syntax, functionality, and real-world examples.
What is regexp_like in PostgreSQL?
The regexp_like() function in PostgreSQL is used to match the string with a specific regular expression pattern. This function returns a Boolean value (TRUE
or FALSE
), depending on whether the string matches the specified pattern. This function is very helpful in checking if the input string confirms a specific pattern/format.
It is similar to other regex functions like regex_replace, regexp_matches, and regexp_split_to_table. However this regexp_like() is specifically for evaluating whether there exists a match between the provided string and given the regular expression pattern or not.
Syntax:
regexp_like(string, pattern , flags)
Key terms:
- string : It is the input string that need to be matched or evaluated.
- pattern : it is the regular expression pattern to match the input string.
- flags(optional) : flags modifies the behavior of the regular expression , including case-insensitive matching or multi-line support matching of string, etc.
Commonly Used Flags
- i - case insensitive matching of input string.
- g - global matching ( find all the matches rather than stopping after the first ).
- m - multi-line mode.
Examples of Using regexp_like() in PostgreSQL
Here are several practical examples that demonstrate the usage of regexp_like
()
in different scenarios. These examples will illustrate how to effectively use this function to filter and validate data in PostgreSQL, improving the overall efficiency of our queries.
Query:
CREATE TABLE employees (
id SERIAL PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
department VARCHAR(50)
);
INSERT INTO employees (name, email, department)
VALUES
('Jonny Doe', '[email protected]', 'HR'),
('Jane Smith', '[email protected]', 'Engineer'),
('Mohit Sigh', '[email protected]', 'Finance'),
('Sara Sharma', '[email protected]', 'Marketing');
Output:
Example 1: Check if a string contains digit or not
This example shows how to use regexp_like
()
to check whether an input string contains any numeric digits. By using the regular expression [0-9]
, we can search for any numbers within the string, making this a useful function for data validation or filtering out entries that include numerical values.
Query:
SELECT regexp_like( 'abc123' , '[0-9]' );
Output
TRUE
Explanation :
The input string "abc123" contains digits "123" which satisfies the regular expression and the regexp_like() functions then return TRUE in response to it.
Example 2: Case-insensitive Matching
In this example, we explain how to perform case-insensitive matching using the regexp_like
()
function. This can be useful when we need to match strings regardless of their letter case, such as checking for text in user inputs or names. By applying the '
i
'
flag, we ensure that both uppercase and lowercase characters are treated equally.
Query:
SELECT regexp_like ( "HelloWorld" , 'helloworld' , 'i' );
Output
TRUE
Explanation :
The input string "HelloWorld" matches with the 'helloworld' because we are using the flag 'i' for case-insensitive matching, hence true is returned.
Example 3: Find Emails with ".com" Domain
This example demonstrates how to use the regexp_like
()
function to find all employees whose email addresses contain the ".com" domain. This is particularly useful when filtering out specific email domains from a dataset, such as identifying corporate or specific domain email addresses.
Query:
SELECT * FROM employees
WHERE regexp_like ( email , '@.*\.com$');
Output
Explanation:
- @.*\.com$ : this pattern matches all the string that starts with @, followed by number of characters (.*), and ends with .com (.\com$).
Example 4: Find Names Starting with "J" and Containing a Space
In this example, we use the regexp_like
()
function to search for employee names that start with the letter "J" and include a space followed by another word. This can be useful for identifying names that match a specific pattern, such as first and last names that begin with certain letters.
Query :
SELECT * FROM employees
WHERE regexp_like ( name , '^J\w*\s\w+' );
Output
Explanation:
The regular expression ^J\w*\s\w+
matches names that start with "J", followed by any number of letters or digits (\w*
), a space (\s
), and at least one more word (\w+
).
Conclusion
The regexp_like() function in PostgreSQL is very powerful way of matching a string using regular expressions, allowing developers to efficiently perform pattern matching, validation, and filtering of string data. With its simple syntax and the ability to use optional flags like case-insensitivity and global matching, regexp_like()
can handle a variety of use cases.
Similar Reads
How to Insert Text With Single Quotes in PostgreSQL
SQL stands for structured query language and is used to query databases for analytical needs. While using arithmetic queries, some results require strings to help them understand better. Strings can be formed by enclosing text in quotes. However in a case when quotes are themselves required in a str
4 min read
How to use Regex in TestNG?
In this article, we will see how to use Regex in TestNG. In TestNG, we can use Regular Expressions for two purposes: To Include Test CasesTo Exclude Test Cases To include test cases we use the include the keyword in the testng.xml configuration file.To Exclude test cases we use the exclude keyword i
5 min read
PostgreSQL - REGEXP_MATCHES Function
The PostgreSQL REGEXP_MATCHES() function is a powerful tool for matching POSIX regular expressions against a string. It returns substrings that satisfy the pattern, making it indispensable for string manipulation, pattern matching, and data extraction tasks. In this article, we will explain the synt
4 min read
PostgreSQL - REGEXP_REPLACE Function
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 matchi
4 min read
PostgreSQL REVERSE() Function
The REVERSE() function in PostgreSQL is a simple yet powerful tool used to reverse the order of characters in a given string. It takes one input which is a string and returns the characters in reverse order. This function is helpful when you need to transform data, run tests or validate information.
4 min read
PostgreSQL - Index Types
Indexes are essential tools in PostgreSQL, allowing you to speed up data retrieval and enhance the performance of the queries. This article will explore the various index types available in PostgreSQL, understand their unique characteristics, and learn how to use them effectively to optimize your da
3 min read
How to Use the IN Operator with a SubQuery in SQL?
In this article, we will see the use of IN Operator with a SubQuery in SQL. IN operator is used to compare the column values with the list of values. The list of values is defined after IN query in SQL. If we don't know the exact list of values to be compared, we can generate the list of values usin
2 min read
What is GIN in PostgreSQL?
The GIN or Generalized Inverted Index, is one of the most powerful indexing techniques in PostgreSQL. It suits best indexing composite values, such as arrays, JSONB, or full-text search. In this article, we will learn about what GIN is, how it works along with their syntax and examples.What is GIN i
4 min read
Can We Use Contains in PostgreSQL?
While PostgreSQL does not have a direct CONTAINS function like some other databases, it offers powerful alternatives for achieving similar functionality. Through the use of operators such as LIKE, ILIKE, and advanced Full-Text Search (FTS) functions like to_tsvector() and to_tsquery().PostgreSQL all
3 min read
What is an Index in PostgreSQL?
PostgreSQL is a powerful and reliable open-source relational database management system (RDBMS) known for its extensive features, including robustness and scalability. One key feature of PostgreSQL that contributes to its high performance is indexing. Proper use of indexes can significantly improve
5 min read