开发者

Regular expression replace in PL/pgSQL

开发者 https://www.devze.com 2022-12-29 03:14 出处:网络
If I have the following input (excluding quotes): \"The ancestralterritorialimperatives of thetrumpeter swan\"

If I have the following input (excluding quotes):

"The ancestral   territorial      imperatives of the    trumpeter swan"

How can I collapse all multiple spaces to a single space so that the input is transformed to:

"The ancestral territorial imperatives of the trumpeter swan"

This is going to be used in a trigger function on insert/update (which already trims leading/trailing spaces). Currently, it raises an exception if the input contains multiple adjacent spaces, but I would rather it simply transforms it into something valid before inserting.

What is the be开发者_运维技巧st approach? I can't seem to find a regular-expression replace function for PL/pgSQL. There is a text_replace function, but this will only collapse at most two spaces down to one (meaning three consecutive spaces will collapse to two). Calling this function over and over is not ideal.


PostgreSQL has a REGEXP_REPLACE function that you should be able to use.

DECLARE
  result VARCHAR2(255);
BEGIN
  result := REGEXP_REPLACE(subject, $$ {2,}$$, $$ $$, 'g');
END;


You could use plperl, and use perl regular expressions for the purpose.

Upgrading is good, but plperl can let you scrape by a little longer.

0

精彩评论

暂无评论...
验证码 换一张
取 消