Python Re. Sub Not Replacing All the Occurance of String

Python Re. Sub Not Replacing All the Occurance of String

I'm not getting the desire output, re.sub is only replacing the last occurance using python regular expression, please explain me what i"m doing wrong

srr = "     "
re.sub("", "", srr)
'image-1CE005XG03'

Desire output without from the above string.

image-1CCCC|image-1VVDD|image-123|image-1CE005XG03
2

4 Answers

I would use re.findall here, rather than trying to do a replacement to remove the portions you don't want:

src = "     "
matches = re.findall(r'https?://www\.\S+#([^|\s]+)', src)
output = '|'.join(matches)
print(output)  # image-1CCCC|image-1VVDD|image-123|image-123|image-1CE005XG03

Note that if you want to be more specific and match only Google URLs, you may use the following pattern instead:

https?://www\.google\.\S+#([^|\s]+)
1
>>> "|".join(re.findall(r'#([^|\s]+)', srr))
'image-1CCCC|image-1VVDD|image-123|image-123|image-1CE005XG03'

Here is another solution,

"|".join(i.split("#")[-1] for i in srr.split("|"))

image-1CCCC|image-1VVDD|image-123|image-123|image-1CE005XG03

Using correct regex in re.sub as suggested in comment above:

import re

srr = "     "
print (re.sub(r"\s*https?://[^#\s]*#", "", srr))

Output:

image-1CCCC|image-1VVDD|image-123|image-123|image-1CE005XG03

RegEx Details:

  • \s*: Match 0 or more whitespaces
  • https?: Match http or https
  • ://: Match ://
  • [^#\s]*: Match 0 or more of any characters that are not # and whitespace
  • #: Match a #

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.