Home > database >  How to remove a string between two words without removing those words?
How to remove a string between two words without removing those words?

Time:12-12

I want to remove a substring between two words from a string with Python without removing the words that delimit this substring.

what I have as input : "abcde" what I want as output : "abde"

The code I have:

import re

s = "abcde"
a = re.sub(r'b.*?d', "", s)

what I get as Output : "ae"

------------Edit :

another example to explain the case :

what I have as input : "c:/user/home/56_image.jpg" what I want as output : "c:/user/home/image.jpg"

The code I have:

import re

s = "c:/user/home/56_image.jpg"
a = re.sub(r'/.*?image', "", s)

what I get as Output : "c:/user/home.jpg"

/!\ the number before "image" is changing so I could not use replace() function I want to use something generic

CodePudding user response:

You can do like bellow:

''.join('abcde'.split('c'))

CodePudding user response:

I would phrase the regex replacement as:

s = "abcde"
a = re.sub(r'b\w*d', "bd", s)
print(a)  # abde

I am using \w* to match zero or more word characters in between b and d. This is to ensure that we don't accidentally match across words.

  • Related