简体   繁体   English

在postgres中的数组列上使用regexp_replace

[英]Using regexp_replace on array column in postgres

I am trying to update all occurrences of some value in every element of an array column using a regexp. 我试图使用正则表达式更新数组列的每个元素中的所有出现的值。

If the column was not of type text[] and text instead I would use this query to update: 如果列不是text[]和text的类型,我会使用此查询来更新:

UPDATE my_table
SET my_column = regexp_replace(
    my_column, 'foo(\d+)', 'bar\1', 'g'
)

How can I replace each element in an array column? 如何替换数组列中的每个元素?

The simplest way as I know: 我知道最简单的方法:

UPDATE my_table SET
  my_column = array(
    SELECT regexp_replace(unnest(my_column), 'foo(\d+)', 'bar\1', 'g'))

PostgreSQL too smart. PostgreSQL太聪明了。 It is possible to use SRF (set returning functions, just google it) as argument of other functions. 可以使用SRF(设置返回函数,只是google)作为其他函数的参数。 For example: 例如:

select abs(unnest('{1,-2,3}'::int[]));

It is same to 它是一样的

select abs(x) from unnest('{1,-2,3}'::int[]) as x;

but shorter. 但更短。

Its returning 它的归来

┌─────┐
│ abs │
╞═════╡
│   1 │
│   2 │
│   3 │
└─────┘

And array(select ...) is just array constructor that transforms select... result to an array. array(select ...)只是将select... result转换为数组的数组构造函数。

Use a CTE to unnest() the array, do the transformation on the array elements and aggregate back to an array which you then use for the UPDATE . 使用CTE unnest()数组,对数组元素进行转换并聚合回一个数组,然后将其用于UPDATE Assuming your table has a primary key: 假设您的表有一个主键:

WITH changed(key, arr) AS (
  SELECT id, array_agg(regexp_replace(col, 'foo(\d+)', 'bar\1', 'g'))
  FROM my_table, unnest(my_column) un(col)
  GROUP BY id
)
UPDATE my_table
SET my_column = arr
FROM changed
WHERE id = key

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM