Search code examples
sqlpostgresqlregexp-replace

How to replace special characters except - (dash)


Using PGAdmin (Postgresql), I'm trying to remove all special characters except the - in the fields.

Current command being used:

regexp_replace(b.DOWNCASE_NAME, '[^\w\s]', '', 'g') as CONDITION_NAME_DC,

That will change "ovarian sertoli-leydig cell tumor" to "ovarian sertolileydig cell tumor"

I used this because there are fields which contain commas, forward slashes and I don't need those. But how do I use regexp_replace to remove those characters except for the - ?


Solution

  • You can exclude the - in the pattern using ^- as shown below

    select regexp_replace('ova@ri/an serto#li-leydi!g cel/l tumor', '[^\w\s^-]', '', 'g') 
    

    Output

    ovarian sertoli-leydig cell tumor
    

    Check demo here