1

I am trying to remove whitespaces from a column in a Postgres table.
I am using SQLAlchemy to do it.

e.g. ' some value ' should become 'some value'.

My code is:

sqlalchemy.func.regexp_replace(
                # replace whitespaces with a single space
                sqlalchemy.func.regexp_replace(source_column_instance, ' {2,}', ' ', 'g'),
                # also remove leading and trailing whitespaces
                '^ | $', '', 'g') 

The above is working fine but I want to merge the two regexes into one.

0

1 Answer 1

2

You may use

sqlalchemy.func.regexp_replace(source_column_instance, '^ +| +$|( ){2,}', '\\1', 'g')

Here,

  • ^ + - matches 1 or more spaces at the start of the string
  • | - or
  • +$- matches 1 or more spaces at the end of the string
  • | - or
  • ( ){2,} - matches and captures a single space into Group 1 two or more times.

The replacement is \1, backreference to Group 1 value, so that only one space is kept in the result where there were two or more spaces.

Sign up to request clarification or add additional context in comments.

5 Comments

it actually works. Thanks a lot. However, it will take me few more minutes to understand the backreference as I have seen it the first time today
Hey, it doesn't work if i have more than one leading space. Can you test that?
@HarisMuzaffar Did you use '^ +| +$|( ){2,}'?
this one works, the first one i.e. '^ | $|( ){2,}' seems to be not working. May be you should try to modify '^ | $|( ){2,}' or remove it from your answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.