Search code examples
sqlregexpostgresqlregexp-replace

How can I replace a word with its root in postgresql?


what I would like to do is something like

select
"wise, wisdom and wiseness have a common root"  as body,
regexp_replace(body,'wis%','wise') 

to obtain

wise --> wise  
wisdom --> wise   
wiseness --> wise 

and so the result would be "wise, wise and wise have a common root"


Solution

  • demo:db<>fiddle

    select
    regexp_replace('wise, wisdom and wiseness have a common root','wis[\w]*','wise','g')
    
    1. RegExp wis[\w]* is searching for all words beginning with wis followed by any number of letters and digits. Use [A-Za-z] instead of [\w] if you only are interested in letters.
    2. Flag g makes it for all occurences.