Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression find and replace in Postgres

I have a table that contains a number of rows with columns containing a URL. The URL is of the form:

http://one.example1.com:9999/dotFile.com

I would like to replace all matches in that column with http://example2.com/dotFile.com while retaining everything after :9999. I have found some documentation on regexp_matches and regexp_replace, but I can't quite wrap my head around it.

like image 894
ringocub Avatar asked Jul 30 '12 13:07

ringocub


People also ask

How do I find and replace in PostgreSQL?

In PostgreSQL, the REPLACE function is used to search and replace all occurrences of a string with a new one. Syntax: REPLACE(source, old_text, new_text ); Let's analyze the above syntax: The source is a string where you want to replace the existing string.

Can I use regex in PostgreSQL?

The simplest use of regex in PostgreSQL is the ~ operator, and its cousin the ~* operator. value ~ regex tests the value on the left against the regex on the right and returns true if the regex can match within the value. Note that the regex does not have to fully match the whole value, it just has to match a part.

How do I remove special characters from a string in PostgreSQL?

Postgresql regexp_replace special charactersSELECT regexp_replace('[email protected]','[^\w]+',''); In the above code, the source is '[email protected]' with the special character @, the pattern is '[^\w]+', which means replacing everything that is not number, digit, underline with the nothing.

How does regex replace work?

The REGEXREPLACE( ) function uses a regular expression to find matching patterns in data, and replaces any matching values with a new string. standardizes spacing in character data by replacing one or more spaces between text characters with a single space.


2 Answers

To replace a fixed string, use the simple replace() function.

To replace a dynamic string, you can use regexp_replace() like this:

UPDATE   YourTable SET   TheColumn = regexp_replace(     TheColumn, 'http://[^:\s]+:9999(\S+)', 'http://example2.com\1', 'g'   ) 
like image 51
Tomalak Avatar answered Sep 16 '22 16:09

Tomalak


if you know the url, you don't have to use regex. replace() function should work for you:

replace(string text, from text, to text)         Replace all occurrences in string of substring from with substring to    example: replace('abcdefabcdef', 'cd', 'XX')    abXXefabXXef 

you could try:

UPDATE yourtable SET   yourcolumn = replace(yourcolumn, 'one.example1.com:9999','example2.com') ; 
like image 39
Kent Avatar answered Sep 17 '22 16:09

Kent