如何在Python中使用re.sub?

How to use re.sub in Python?

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

我想删除 python

中的 <c> code </c> 语句
output = "<a> text </a>"

在这里我们可以简单地在捕获组中添加开始和结束标签以及两者之间的所有内容:

# 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 = ``;

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

console.log('Substitution result: ', result);

您可以使用 re.sub:

>>> import re
>>> text = "<a> text </a> <c> code </c>"
>>> new_text = re.sub(r'<c>.*?</c>', '', text)
>>> new_text
<a> text </a> 
 import re
 text = "<a> text </a> <c> code </c>"
 rg = r"<c>.*<\/c>"
 for match in re.findall(rg, text):
     text = text.replace(match, "")