首页 > 解决方案 > 在 postgres 中匹配 regexp_replace 中的 2 个条件

问题描述

我需要帮助在 Postgres regexp_replace 中正确获取我的正则表达式语法:我的字符串:

1ABC 2ABC 3DEF 4DEF  

我的 2 个匹配/替换条件是:

 Replace: A OR C but not in front of 2
    or
 Replace: D OR F but not in front of 4

所以我期待得到:

"1A;BC; 2ABC; 3D;EF; 4DEF;"

我对条件 1 的部分替换是:

SELECT regexp_replace('1ABC 2ABC 3DEF 4DEF', '((?<!2)(A|C))','\1;','g' );

我的“替换”实际上是匹配文字之后的“插入”。

我似乎无法找到第二个条件的模式,而不破坏整个事情。这甚至可以在 1 条语句中实现吗?

标签: postgresqlregexp-replace

解决方案


SELECT regexp_replace('1ABC 2ABC 3DEF 4DEF', '((\w*[^2]A|C)|(\w*[^4]D|F))','\1;','g');

结果:1A;BC; 2ABC; 3D;EF; 4DEF;


推荐阅读