In addition to removing the space around the brackets you also want to transform the[
into the [
To handle this and remove any number / type of spaces around the text in brackets, you can do the following
>>> import re
>>> text = 'i want to go to the[ super mall ](place)'
>>> re.sub(r'(\w)\[\s+(.*?)\s+\]', r'\1 [\2]', 'i want to go to the[ super mall ](place)')
'i want to go to the [super mall](place)'
We can look at the first two arguments to re.sub
in further detail (the last argument is just the string to operate on).
First we have this regex r'(\w)\[\s+(.*?)\s+\]'
(\w)\[
matches a word and a bracket and stores the word for use later using parentheses, (matches the[
in the original string)
\s+
matches one or more whitespace characters (matches
in the original string)
(.*?)
matches any text within the brackets and spaces and stores this text for use later using parentheses (matches super mall
in the original string)
\s+\]
matches one or more whitespace characters and the closing bracket (matches ]
in the original string)
From that regex, we have stored two strings (the
and super mall
) and matched this entire substring the[ super mall ]
.
Next we have the template to replace that entire substring with: \1 [\2]
. this uses the stored strings from earlier to replace \1
and \2
respectively.