postgresql regexp_replace: how to replace captured group with evaluated expression (adding an integer value to capture group)

丶灬走出姿态 提交于 2020-12-30 06:23:29

问题


I need to convert some strings with this format:

B12F34

to something like that:

Building 12 - Floor 34

but I have to add a value, say 10, to the second capture group so the new string would be as:

Building 12 - Floor 44

I can use this postgres sentence to get almost everything done, but I don't know how to add the value to the second capture group.

SELECT regexp_replace('B12F34', 'B(\d+)F(\d+)', 'Building \1 - Floor \2', 'g');

I have been searching for a way to add a value to \2 but all I have found is that I can use 'E'-modifier, and then \1 and \2 need to be \\1 and \\2:

SELECT regexp_replace('B12F34', 'B(\d+)F(\d+)', E'Building \\1 - Floor \\2', 'g')

I need some sentence like this one:

SELECT regexp_replace('B12F34', 'B(\d+)F(\d+)', E'Building \\1 - Floor \\2+10', 'g')

to get ........ Floor 44 instead of ........ Floor 34+10

Thanks in advance!


回答1:


You can not do this in regexp alone because regexp does not support math on captured groups even if they are all numeric characters. So you have to get the group that represents the floor number, do the math and splice it back in:

SELECT regexp_replace('B12F34', 'B(\d+)F(\d+)', 'Building \1 - Floor ') ||
       ((regexp_matches('B12F34', '[0-9]+$'))[1]::int + 10)::text;

Not very efficient because of the two regexp calls. Another option is to just get the two numbers in a sub-query and assemble the string in the main query:

SELECT format('Building %L - Floor %L', m.num[1], (m.num[2])::int + 10)
FROM (
  SELECT regexp_matches('B12F34', '[0-9]+', 'g') AS num) m;


来源:https://stackoverflow.com/questions/36061626/postgresql-regexp-replace-how-to-replace-captured-group-with-evaluated-expressi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!