Des*_*.F. 6 regex postgresql replace
我需要使用以下格式转换一些字符串:
B12F34
这样的事情:
12楼 - 34楼
但我必须向第二个捕获组添加一个值,比方说10,所以新字符串将如下:
12楼 - 44楼
我可以使用这个postgres句子来完成几乎所有的事情,但我不知道如何将值添加到第二个捕获组.
SELECT regexp_replace('B12F34', 'B(\d+)F(\d+)', 'Building \1 - Floor \2', 'g');
Run Code Online (Sandbox Code Playgroud)
我一直在寻找一种方法来为\ 2添加一个值,但我发现的是我可以使用'E'修饰符,然后\ 1和\ 2需要是\\ 1和\\ 2:
SELECT regexp_replace('B12F34', 'B(\d+)F(\d+)', E'Building \\1 - Floor \\2', 'g')
Run Code Online (Sandbox Code Playgroud)
我需要一些像这样的句子:
SELECT regexp_replace('B12F34', 'B(\d+)F(\d+)', E'Building \\1 - Floor \\2+10', 'g')
Run Code Online (Sandbox Code Playgroud)
得到........ 44楼 而不是........ 34楼+10
提前致谢!
你不能单独在regexp中执行此操作,因为regexp不支持捕获组的数学,即使它们都是数字字符.因此,您必须获得代表楼层编号的组,进行数学计算并将其拼接回:
SELECT regexp_replace('B12F34', 'B(\d+)F(\d+)', 'Building \1 - Floor ') ||
((regexp_matches('B12F34', '[0-9]+$'))[1]::int + 10)::text;
Run Code Online (Sandbox Code Playgroud)
由于两个正则表达式调用,效率不高.另一种选择是在子查询中获取两个数字并在主查询中组合字符串:
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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5225 次 |
| 最近记录: |