Home > Enterprise >  Remove Space Before and Atfer a Specific Character Using Regex
Remove Space Before and Atfer a Specific Character Using Regex

Time:07-04

Can anyone show me how to remove spaces before and after a hyphen? The code below works on removing the space fore the hyphen but I need to removed before and after the hyphen.

#!/usr/bin/python3

import re

test_strings = ["(1973)          -trailer.mp4", "(1973)-    fanart.jpg", "(1973)    -           poster.jpg"]

for i in test_strings:
        res =  re.sub('  -', '-', i)
        print (res)

CodePudding user response:

You could probably do it in a single regex, but since I'm sometimes lazy, just chain two together, like:

#!/usr/bin/python3

import re

test_strings = ["(1973)          -trailer.mp4", "(1973)-    fanart.jpg", "(1973)    -           poster.jpg"]

for i in test_strings:
    res =  re.sub('-  ','-', re.sub('  -', '-', i))
    print (res)

Edit: MrGeek has a better answer in a comment.

CodePudding user response:

You can use pattern \s*-\s* where \s to represent any whitespace character, if you strictly want to use space then you can just use space character in the pattern i.e. *- *.

>>> pattern = re.compile('\s*-\s*')
>>> [pattern.sub('-', item) for item in test_strings]

#output:
['(1973)-trailer.mp4', '(1973)-fanart.jpg', '(1973)-poster.jpg']
  • Related