我正在寻找一种简单/高效/优雅的方式来替换字符串中给定字符的所有实例,除非它是由其他特定字符框起来的。例如:
我想用#
替换字符串a,b,c,"d,e,f,g",h,i,j
中的所有,
字符,除非它们是用"
框起来的。预期结果为:a#b#c#"d,e,f,g"#h#i#j
。
欢迎任何想法。
以下是我作为PL/pgSQL块的建议,如果相关,可以将其修改/成形为函数
基本上,它提取、存储并替换";免疫的";字符串的一部分(用双引号括起来(,用散列替换逗号,然后替换回";免疫的";零件。IMMUNE_PATTERN
可能也需要修改。
do language plpgsql
$$
declare
target_text text := 'a,b,c,"d,e,f,g",h,i,"d2,e2,f2,g2",j'::text;
IMMUNE_PATTERN constant text := '__%s__';
immune_parts text[];
immune text;
i integer;
begin
immune_parts := array(select * from regexp_matches(target_text,'"[^"]+"','g'));
for immune, i in select * from unnest(immune_parts) with ordinality loop
target_text := replace(target_text, immune, format(IMMUNE_PATTERN, i));
end loop;
target_text := replace(target_text, ',', '#');
for immune, i in select * from unnest(immune_parts) with ordinality loop
target_text := replace(target_text, format(IMMUNE_PATTERN, i), immune);
end loop;
raise notice '%', target_text;
end;
$$;
结果是a,b,c,"d,e,f,g",h,i,"d2,e2,f2,g2",j
变成a#b#c#"d,e,f,g"#h#i#"d2,e2,f2,g2"#j