2
Text = "<a> text </a> <c> code </c>"                                               

I want to remove <c> code </c> statement in python

output = "<a> text </a>"
Emma
  • 27,428
  • 11
  • 44
  • 69

3 Answers3

4

You can use re.sub:

>>> import re
>>> text = "<a> text </a> <c> code </c>"
>>> new_text = re.sub(r'<c>.*?</c>', '', text)
>>> new_text
<a> text </a> 
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
1

Here we can simply add both opening and closing tags and everything in between in a capturing group:

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"(<a>.+<\/a>)"

test_str = "<a> text </a> <c> code </c>"

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

Demo

const regex = /(<a>.+<\/a>).+/gm;
const str = `<a> text </a> <c> code </c>`;
const subst = `$1`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);
Emma
  • 27,428
  • 11
  • 44
  • 69
  • 2
    They just want to remove it, not do... all of this ^ – cs95 May 20 '19 at 00:32
  • 1
    The premise behind this is incorrect. What if OP actually has some tag ` ... ` that they implicitly want to keep? They've stated that want to remove ` ... `, leaving everything else unchanged. Your tacit assumption that there are only two types of tags isn't a reasonable one. – cs95 May 20 '19 at 00:35
1
 import re
 text = "<a> text </a> <c> code </c>"
 rg = r"<c>.*<\/c>"
 for match in re.findall(rg, text):
     text = text.replace(match, "")