简体   繁体   中英

How do I remove a string between two characters in PostgreSQL?

I have a column containing address information. I want to remove everything between # and , but also remove the # and leave the , .

EDIT: I also need to remove the space leading the # .

Here is what my column looks like:

ADDRESS
123 abc st. #123, city, zipcode
321 def road #321, city, zipcode

So my column would look like this:

ADDRESS
123 abc st., city, zipcode
321 def road, city, zipcode

Based on your example, you also want to remove the space before the # :

select str, regexp_replace(str, ' #[^,]+,', ',')
from (values ('321 def road #321, city, zipcode')) v(str)

You can use positive lookahead :

 select address, regexp_replace(address,' #[^,]+(?=,)','') from foo; 
\naddress |  regexp_replace              \n:------------------------------- |  :-------------------------- \n123 abc st.  #123, city, zipcode |  123 abc st., city, zipcode  \n321 def road #321, city, zipcode |  321 def road, city, zipcode \n

db<>fiddle here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM