Last active
March 10, 2021 13:23
-
-
Save xoelop/aa718a698865d425fadb1e5f21c5515c to your computer and use it in GitHub Desktop.
Function to escape special characters in a pattern in Postgres. This is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE OR REPLACE FUNCTION public.regexp_quote(IN TEXT) | |
RETURNS TEXT | |
LANGUAGE plpgsql | |
STABLE | |
AS $$ | |
/******************************************************************************* | |
* Function Name: regexp_quote | |
* In-coming Param: | |
* The string to decoded and convert into a set of text arrays. | |
* Returns: | |
* This function produces a TEXT that can be used as a regular expression | |
* pattern that would match the input as if it were a literal pattern. | |
* Description: | |
* Takes in a TEXT in and escapes all of the necessary characters so that | |
* the output can be used as a regular expression to match the input as if | |
* it were a literal pattern. | |
* Source: https://cwestblog.com/2012/07/10/postgresql-escape-regular-expressions/ * | |
* The original one doesn't work anymore. | |
******************************************************************************/ | |
BEGIN | |
RETURN REGEXP_REPLACE($1, '([\.\+\*\?\^\$\(\)\[\]\{\}\|\\])', '\\\1', 'g'); | |
END; | |
$$ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment