如何在Python中使用re.sub?

时间:2019-05-20 00:22:21

标签: python regex string regex-group regex-greedy

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

我要删除python中的<c> code </c>语句

output = "<a> text </a>"

3 个答案:

答案 0 :(得分:4)

您可以使用re.sub

>>> import re
>>> text = "<a> text </a> <c> code </c>"
>>> new_text = re.sub(r'<c>.*?</c>', '', text)
>>> new_text
<a> text </a> 

答案 1 :(得分:1)

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

# 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);

答案 2 :(得分: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, "")