guilty guy
guilty guy

Reputation: 13

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

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

Upvotes: 1

Views: 237

Answers (3)

The fourth bird
The fourth bird

Reputation: 163207

You are also matching what you want to keep with an empty string, that is why you don't see it in the replacement.

You can use capture groups and use the group in the replacement, or lookarounds which are non consuming.

For example, using group 1 using \1 in the replacement:

(b)\w*?(?=d)

Regex demo

Or using a lookaround, and use an empty string in the replacement.

\d+_(?=image)

Regex demo

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520928

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.

Upvotes: 0

Mohammad Khoshbin
Mohammad Khoshbin

Reputation: 616

You can do like bellow:

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

Upvotes: 1

Related Questions