0

I am using re but I am not having any luck. I want to know how to remove spaces in between braces. For example

I have this string

     i want to go to the[ super mall ](place)

You see the the space in "[ super mall]"?

What can turn this string into

      i want to go to the [super mall](place)

I would appreciate any help I can get on this thanks.

Mystery Man
  • 535
  • 2
  • 7
  • 20

3 Answers3

2

I'm assuming braces are balanced and cannot be nested.

>>> import re
>>> s = 'i want to go to the[super mall](place) [ for real    ]'
>>> re.sub('\[\s*(.*?)\s*\]', r'[\1]', s)
'i want to go to the[super mall](place) [for real]'

It doesn't work for multiple ones. like i want to go to the [ super mall ](place) and [ cheese mall ](place)

I think it does.

>>> s = 'i want to go to the [ super mall ](place) and [ cheese mall ](place)'
>>> re.sub('\[\s*(.*?)\s*\]', r'[\1]', s)
'i want to go to the [super mall](place) and [cheese mall](place)'
timgeb
  • 76,762
  • 20
  • 123
  • 145
0

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.

0

You can use groups and backreferencing to solve this:

string = 'i want to go to the[ super mall ](place)'
re.sub('\[ (.+) \]', '[\g<1>]', string)

Here I am assuming that you always have atleast one character, padded with one space on each side, within the brackets.

This will give you 'i want to go to the[super mall](place)'

See re docs: https://docs.python.org/3/library/re.html#re.sub

hvassup
  • 159
  • 5