【问题标题】:How can I replace a duplicate word in a specific condition using REGEXP_REPLACE?如何使用 REGEXP_REPLACE 替换特定条件下的重复单词?
【发布时间】:2021-11-01 10:40:36
【问题描述】:

我基本上需要在某种条件下替换重复的单词,但是该单词在整个字符串中出现了很多次。那么我该如何转换呢:

') test test test'

进入这个:

') test successful successful'

我尝试使用它和它的其他一些变体,但没有一个奏效:

SELECT regexp_replace(') test test', '!~*[)] test|test)', 'succesful','gi')

【问题讨论】:

    标签: regex postgresql duplicates conditional-statements regexp-replace


    【解决方案1】:

    您要查找的内容通常需要支持可变长度后视的正则表达式引擎,因为只有出现的 test 以及至少出现一次的 test 才会被替换。

    要解决 PostgreSQL 中缺少此类支持的问题,您可以将第一次出现的 test 替换为在任何给定输入中极不可能出现的虚拟文本,然后继续替换其余的出现将test 替换为successful,最后将虚拟文本替换回test

    SELECT replace(replace(regexp_replace(') test test test', ' test', '!!dummy!!'), ' test', ' successful'), '!!dummy!!', ' test')
    

    演示:https://extendsclass.com/postgresql/7d9cfe4

    【讨论】:

      猜你喜欢
      • 2021-07-21
      • 2020-02-01
      • 1970-01-01
      • 2018-08-05
      • 1970-01-01
      • 2020-01-21
      • 2022-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多