1
votes

I have the following string:

res = '(321, 3)-(m-5, 5) -(31,1)'

I wanna remove the whitespace withing the bracket but i haven't any knowledge about regular expression

I ve try this but that doesn't work:

import re
res = re.sub(r'\(.*\s+\)', '', res)
3
You only want to remove the whitespace inside the brackets, leaving the whitespace outside the brackets untouched? So your result would be '(321,3)-(m-5,5) -(31,1)'? - TigerhawkT3
Yes this what i want - mazouu rahim
Do you have strings with nested brackets like ( (1, 2) - 3 )? - Jon

3 Answers

3
votes

You can substitute a non-greedy wildcard match for characters in parentheses with a function that splits the match on whitespace and rejoins it.

>>> import re
>>> res = '(321, 3)-(m-5, 5) -(31,1)'
>>> re.sub(r'\(.*?\)', lambda x: ''.join(x.group(0).split()), res)
'(321,3)-(m-5,5) -(31,1)'
0
votes

You could convert the string into a list, go through each letter and count if you are within brackets or not. In toRemove, you collect the positions of whitespaces, which you then remove from the list. Then you convert the list back to a string ...

res = '(321, 3)-(m-5, 5) -(31,1)'
r = list(res)
insideBracket = 0
toRemove = []
for pos,letter in enumerate(r):
    if letter == '(':
        insideBracket += 1
    elif letter == ')':
        insideBracket -= 1
    if insideBracket > 0:
        if letter == ' ':
            toRemove.append(pos)

for t in toRemove[::-1]:
    r.pop(t)

result = ''.join(r)
print(result)
0
votes

I think regular expressions aren't quite powerful enough to do what you want here; you want to remove all whitespace that's found in between parenthesis characters. The trouble is, solving this for the general case means you're doing a context-sensitive match on the string, and regular expressions are mostly context-insensitive, and so can't do your job. There are lookaheads and lookbehinds that can restrict matches to particular contexts, but they won't solve your problem in the general case either:

The contained pattern must only match strings of some fixed length, meaning that abc or a|b are allowed, but a* and a{3,4} are not. Group references are not supported even if they match strings of some fixed length.

Because of this, I would match the parenthesis groups first:

>>> re.split(r'(\([^)]*\))', res)
['', '(321, 3)', '-', '(m-5, 5)', ' -', '(31,1)', '']

and then remove whitespace from them in a second step before joining everything back up into a single string:

>>> g = re.split(r'(\([^)]*\))', res)
>>> g[1::2] = [re.sub(r'\s*', '', x) for x in g[1::2]]
>>> ''.join(g)
'(321,3)-(m-5,5) -(31,1)'