I am trying to remove a substring using regex in Python.
The substring could be the entire string, at the beginning, in the middle, or at the end.
The goal is that the resulting string should not have extra spaces where the substring existed.
Could you suggest a simple and efficient regex that achieves this?
Here are examples of the scenarios*, and my expected results:
'before remove after' --> 'before after' (separated by single space)
'remove after' --> 'after' (no space)
'before remove' --> 'before' (no space)
'remove' --> '' (no space, empty string)
* before, remove, and after may themselves internally contain any character (letters, numbers, spaces, etc.).
The regex should achieve the following:
- If there was text before and text after the substring, the two parts should be separated by a single space.
- If there was only text before the substring, the result should not have a space at the end.
- If there was only text after the substring, the result should not have a space in the beginning.
- If there was no text before and no text after the substring, the result should be an empty string.
Here are a couple of my attempts, but I could not get all scenarios to work...
import re
s1 = 'before remove after'
s2 = 'remove after'
s3 = 'before remove'
s4 = 'remove'
# (1) Just replace with empty string ''...
re.sub(r'remove', '', s1)
'before after' # <-- bad (two spaces in result)
re.sub(r'remove', '', s2)
' after' # <-- bad (space in the beginning)
re.sub(r'remove', '', s3)
'before ' # <-- bad (space at the end)
re.sub(r'remove', '', s4)
'' # <-- good (empty string)
# (2) Capture the "before" part excluding space suffixes,
# capture the "after" part excluding space prefixes,
# and recombine them with a single space...
re.sub(r'(.*?)\s*remove\s*(.*?)', '\\1 \\2', s1)
'before after' # <-- good (single space)
re.sub(r'(.*?)\s*remove\s*(.*?)', '\\1 \\2', s2)
' after' # <-- bad (space in the beginning)
re.sub(r'(.*?)\s*remove\s*(.*?)', '\\1 \\2', s3)
'before ' # <-- bad (space at the end)
re.sub(r'(.*?)\s*remove\s*(.*?)', '\\1 \\2', s4)
' ' # <-- bad (should be an empty string)