Postgres使用regexp_replace匹配某个位置的字符并替换

问题描述 投票:0回答:2

我需要检查字符串的前2个字符是否与'00'或'01'或'02匹配,并分别替换为'24'或'25'或'26'。

所以例如替换

'02:00:00' with  '26:00:00'

我尝试:

SELECT replace(replace(replace('01:01:00'::varchar, '00:', '24:'),'01:', '25:'), '02:', '26:')

不起作用,因为它返回:

"25:25:00"

我只希望匹配条件为前2个字符:

"25:01:00"

也许regexp_replace是正确的方法,但我找不到解决方案。

regex string postgresql replace
2个回答
2
投票

这是我之前的Oracle示例的PostgreSQL版本,逻辑上做同样的事情。有时你需要RTFM! :-)它使用substring()函数返回第一组中的第一个元素,该函数经过测试,与要替换的值交换,与从第二个子串中的组返回的字符串的其余部分连接在一起()打电话。

select 
  case substring(str from '^(\d{2}:)')
    when '00:' then '24:'
    when '01:' then '25:'
    when '02:' then '26:'
    else substring(str from '^(\d{2}:)')
  end || substring(str from '^\d{2}:(\d{2}:\d{2})$') as fixed
from tbl;

SQL Fiddle example

More regex info


1
投票
select regexp_replace('01:01:03', '([0-9]{2})(:[0-9]{2}:[0-9]{2})', 'aa\2');

有两组首先有2个数字,第二组有其他一切。替换意味着打印新字符串,以及其他所有/第二组。

UPDATE

谢谢@franco_b。这是更新更多条目的版本:

select(regexp_replace('01:01:03','([0-9] {2})(:[0-9] {2}:[0-9] {2})','\ 1') :: int + 24):: text || regexp_replace('01:01:03','([0-9] {2})(:[0-9] {2}:[0-9] {2 })','\ 2');

© www.soinside.com 2019 - 2024. All rights reserved.