mapping dom
mapping dom

Reputation: 1955

regexp_replace in postgres keep only desired with single space

What i'd like is to turn a string like this;

10 - 15 st. pan,cras

to

10 - 15 ST PANCRAS

I get most of the way with

 `select upper(regexp_replace('10  -  15 st.  pan,cras', '[^a-zA-Z 0-9-]', '', 'g'));`

But i can't seem to remove the double spaces around the number. I've tried, adding an extra space in the expression;

 `select upper(regexp_replace('10  -  15 st.  pan,cras', '[^a-zA-Z  0-9-]', '', 'g'));`

But no difference in outcome. I'm using regexp_replace as i find the substring syntax harder to follow. On 9.6 string is stored in text

Upvotes: 1

Views: 919

Answers (1)

Vao Tsun
Vao Tsun

Reputation: 51466

you can add space collapsing to only one expression, like this:

t=# select regexp_replace('q            q','( ){1,}',' ','g');
 regexp_replace
----------------
 q q
(1 row)

It replaces with single space if finds one or more following spaces in a row.

so in your case will be

t=# select regexp_replace(upper(regexp_replace('10  -  15 st.  pan,cras', '[^a-zA-Z 0-9-]', '', 'g')),'( ){1,}',' ','g');
   regexp_replace
--------------------
 10 - 15 ST PANCRAS
(1 row)

Upvotes: 1

Related Questions