Python - regex cleanup for any brackets

Viewed 83

My code needs to clean up the whitespace around brackets of any kind, so I assume using regex is my best course of action. My strings will (I think) always look like the following (although more robustness is always appreciated):

text = "the people ( that don't still like / love you } are going to ..."

to look like:

final = "the people (that don't still like / love you} are going to ..."

My current attempt seems to do nothing (I know it only considers round brackets for now):

final = re.sub( r'\s[\(]+\s(\w*)\s[\)]+\s' , '\s[\(]+\1[\)]+\s' , text )

Please & thank you.

1 Answers

In your example string, you want to remove spaces after the opening and before the closing bracket for not the same type of brackets.

The pattern that you tried does not work as there are multiple words between ( and ) and you are not matching the }

Note that in the character class you don't have to escape the parenthesis.

([{[(])\s*(.*?)\s*([]})])

Explanation

  • ([{[(]) Capture group 1 match any of the listed brackets
  • \s* Match 0+ whitespace chars
  • (.*?) Capture group 2, match any char, as least as possible
  • \s* Match 0+ whitespace chars
  • ([]})]) Capture group 3 match any of the listed brackets

See a regex demo

Replace with 3 capturing groups.

\1\2\3
Related