44

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.

2 Answers 2

79

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'
  )
Sign up to request clarification or add additional context in comments.

4 Comments

replace() does a simpler job here, as already you commented yourself. However, to replace "all matches" with regexp_replace(), you have to add the 4th parameter 'g' .. for "globally".
@Erwin Thanks for the hint. I've included that.
I was looking for one I can use in a where clause like ` UPDATE ... WHERE "email" = regexp_matches("email", E'.[co.tz]')` so to filter and improve the update speed. But this is alright too, since I'm only doing this once, in developement. Thank you, for I really wanted a regexp solution tho. :)
If no part of your search string is variable, using regex is pointless. Since regex are much slower than basic string searches I would try to avoid them whereever possible. A "last 5 characters of the column = 'co.tz'" type of search will be faster than the regex equivalent.
38

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')
;

2 Comments

Thanks , that did the trick. update table SET field = replace(field, 'one.example1.com:9999','example2.com')
This comment is what the answer is missing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.