Format CPF column with regular expression

Asked

Viewed 3,054 times

3

In a table containing the column CPF I would like to format it in order to present the content properly. By appropriate way I refer to the format 999.999.999-99. It is possible to format this content through regular expression?

inserir a descrição da imagem aqui

Sqlfiddle for the test

2 answers

4


What you want is possible using the function regexp_replace:

SELECT REGEXP_REPLACE(cpf,
        '([[:digit:]]{3})([[:digit:]]{3})([[:digit:]]{3})([[:digit:]]{2})',
        '\1.\2.\3-\4') AS cpf_formatado
FROM cadastro;

The regular expression will divide the digits into 3 groups of 3 and the end into a group of 2. Finally these groups are reordered with the divisions '\1.\2.\3-\4'.

Example in sqlfiddle.

0

It is not a good practice in database to store already formatted data. It is up to the programmer to format the data in the best way when displaying in the interface, the function of the database is only to provide this data, in a raw way.

  • I do not want to store the data. I want to recover the data and on top of the CPF column apply a formatting.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.