Home > Mobile >  Re sub strings any string starting with <a href or simply href
Re sub strings any string starting with <a href or simply href

Time:06-16

Context: I am removing HTML tags from strings, but for some reason some href tags are still showing up. To avoid this, I'd like to create another re.sub to remove these tags

For example this text:

<a href="/p76643761#p76643761active That's nice

Should be replace with empty string and output should just be That's nice,etc

Function I have (isn't removing href tags for some reason)

def remove_html_tags(text):
    text = re.sub('<[^<] ?>', '', text)

    return text

Thank you all!

CodePudding user response:

You could use <a href=\S \s

def remove_html_tags(text):
    return re.sub(r'<a href=\S \s', '', text)

CodePudding user response:

This will solve your example. It's strange you have an <a href tag that doesn't close though

def remove_html_tags(text):
    if text.startswith("<a href="):
        return text.split()[1:]

text = """<a href="/p76643761#p76643761active That's nice"""
print(remove_html_tags(text))

That's nice
  • Related