【问题标题】:Postgres regexp replace not workingPostgres 正则表达式替换不起作用
【发布时间】:2017-05-13 00:43:50
【问题描述】:

我正在尝试为此查询创建一个正则表达式:

SELECT gruppo
FROM righe_conto_ready
WHERE regexp_replace(gruppo,'(\[{1})|(\].*?\[)|(\].*$)','','g') = '[U6][U53]'
LIMIT 10

这是“gruppo”列的示例:

[U6]  CAFFETTERIA   [U43]  THE E TISANE

我目前正在使用此查询进行测试:

SELECT regexp_replace(gruppo,'(\[{1})|(\].*?\[)|(\].*$)','','g') FROM ....

它只返回U6

如何更改正则表达式以删除括号外的所有内容?

【问题讨论】:

  • 括号外是什么?
  • 试试'\[|\][^][]*\[|\][^][]*$'正则表达式。

标签: regex postgresql regexp-replace


【解决方案1】:

您可以将regexp_matches() 与更简单的正则表达式一起使用:

with righe_conto_ready(gruppo) as (
    select '[U6]  CAFFETTERIA   [U43]  THE E TISANE'::text
)

select gruppo
from righe_conto_ready, 
lateral regexp_matches(gruppo, '\[.+?\]', 'g') matches
group by 1
having string_agg(matches[1], '') = '[U6][U43]'

                 gruppo                  
-----------------------------------------
 [U6]  CAFFETTERIA   [U43]  THE E TISANE
(1 row) 

当您在寻找某个模式的多个匹配项时,regexp_matches() 似乎比regexp_replace() 更自然。

您还可以在括号中搜索前两个子字符串(没有g 标志,该函数产生的行数不超过一行):

select gruppo
from righe_conto_ready, 
lateral regexp_matches(gruppo, '(\[.+?\]).*(\[.+?\])') matches
where concat(matches[1], matches[2]) = '[U6][U43]'

【讨论】:

  • 这对我有帮助...谢谢!
猜你喜欢
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 2013-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多