正则表达式在Postgres中查找和替换

rin*_*cub 30 regex postgresql

我有一个表,其中包含许多行,其中包含一个包含URL的列.URL的格式如下:

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

我希望替换该列中的所有匹配项,http://example2.com/dotFile.com同时保留以下内容后的所有内容:9999.我在regexp_matches和regexp_replace上找到了一些文档,但我无法完全理解它.

Tom*_*lak 59

要替换固定字符串,请使用简单replace()函数.

要替换动态字符串,您可以regexp_replace()像这样使用:

UPDATE
  YourTable
SET
  TheColumn = regexp_replace(
    TheColumn, 'http://[^:\s]+:9999(\S+)', 'http://example2.com\1', 'g'
  )
Run Code Online (Sandbox Code Playgroud)

  • `replace()`在这里做一个更简单的工作,就像你已经评论过的那样.但是,要用`regexp_replace()`替换"所有匹配",你必须为"全局"添加第4个参数`'g'`.. (9认同)

Ken*_*ent 31

如果你知道网址,你不必使用正则表达式.replace()函数应该适合你:

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

你可以尝试:

replace(yourcolumn, 'one.example1.com:9999','example2.com')
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,这就是诀窍.更新表SET字段=替换(字段,'one.example1.com:9999','example2.com') (6认同)