How to remove sub-string starting and ending with something?

Viewed 494

How can I remove a sub-string from a string starting and ending with a certain character combination like:

' bla <span class=""latex""> ... This can be different1 ... </span> blub <span class=""latex""> ... This can be different2 ... </span> bleb'

That I want as result:

'bla blub bleb'

I tried something like this

string.replace('<span class=""latex"">' * '</span>', '')

but this does not work.

Is there a way to implement this?

4 Answers

Read about re.sub function.

A simple example:

import re

s = ' cvbcx cvbcx <span class=""latex""> ... This can be different ... </span>vcvbcxbvxc'
re.sub(r'<span class=""latex"">.+</span>', '<span class=""latex""></span>', s)

>> ' cvbcx cvbcx <span class=""latex""></span>vcvbcxbvxc'

This could work:

>>> import re
>>> x=re.sub(r"""<span class=""latex"">.+?</span>""", "", s)

>>> x
' bla  blub  bleb'

Regex101

EDIT : after clarification by the OP, changed the answer to use lazy quantifier instead of capturing group. While this works, it is not scalable to more complex cases. If that is the case, the proper solution would be to parse the string and extract what is needed.

You will need to use groups if you want some parts and not others.

import re

s = ' cvbcx cvbcx <span class=""latex""> ... This can be different ... </span>vcvbcxbvxc'
r = re.search( r'(<span class=""latex"">)(.+)(</span>)', s)

print(s)
# cvbcx cvbcx <span class=""latex""> ... This can be different ... </span>vcvbcxbvxc

# print(r)
# <re.Match object; span=(13, 73), match='<span class=""latex""> ... This can be different >

print(r.group(1), r.group(3))
# <span class=""latex""> </span>

If you want to keep the data in between:

    >>> x
'<span class=""latex""> ... This can be different ... </span>'
>>> 
>>> d = re.sub('<(/)?span(\ class=\"\".*\"\")?(>)', '', x)
>>> 
>>> d
' ... This can be different ... '
>>> 

If you want to keep the tags:

>>> x
'<span class=""latex""> ... This can be different ... </span>'
>>> 
>>> 
>>> 
>>> new_data = 'abc 123 456'
>>> 
>>> 
>>> d = re.sub('\">.*</','\">{}</'.format(new_data),x)
>>> 
>>> 
>>> d
'<span class=""latex"">abc 123 456</span>'
>>> 
>>> 
>>> 
Related