Home > other >  Postgres: How to replace chars with different patterns?
Postgres: How to replace chars with different patterns?

Time:06-01

I have a bunch a chars that I want to detect to change it for their equivalents in a query in postgres.

For example, If I have this string 'Résidence du Château de Salles' I want to change the char 'é' by the char 'e' and the char 'â' by the char 'a'.

The only way to change the 'â' and the 'é' at the same time is concatening the instruction of regexp_replace of postgres like this:

select lower(regexp_replace(regexp_replace('Résidence du Château de Salles', 'é', 'e', 'g'), 'â', 'a', 'g'));

If I want to change this block of chars by ther equivalents: âêîôû -> aeiou, äËïöü -> aeiou, áéíóú -> aeiou, àèìòù -> aeiou, ñ -> n, ç -> c

I have to concat a bunch of functions of regexp_replace. Each function of each character:

select lower(regexp_replace(regexp_replace(regexp_replace(regexp_replace(regexp_replace('Résidence du Château de Salles', ..............................);

Is there any other best way to do this?

CodePudding user response:

If you only want to replace single characters with another character, translate() is an easier option:

select translate('Résidence du Château de Salles', 'éâ', 'ea') 
  • Related