【问题标题】:How to use re.sub in Python? [duplicate]如何在 Python 中使用 re.sub? [复制]
【发布时间】:2019-10-06 08:36:23
【问题描述】:
Text = "<a> text </a> <c> code </c>"                                               

我想删除python中的&lt;c&gt; code &lt;/c&gt;语句

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

【问题讨论】:

  • 使用类似re.sub(r'&lt;c&gt;.*?&lt;/c&gt;', '', Text)的东西。
  • 也许相关(并且绝对有趣):stackoverflow.com/questions/1732348/…您确定正则表达式是解决您问题的正确工具吗?
  • 谢谢,工作正常

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


【解决方案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);

【讨论】:

  • 他们只是想删除它,而不是......所有这些^
  • 这背后的前提是错误的。如果 OP 实际上有一些标签 &lt;b&gt; ... &lt;/b&gt; 他们隐含地想要保留怎么办?他们表示要删除&lt;c&gt; ... &lt;/c&gt;,而其他所有内容都保持不变。你默认只有两种类型的标签是不合理的。
【解决方案2】:

你可以使用re.sub:

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

【讨论】:

    【解决方案3】:
     import re
     text = "<a> text </a> <c> code </c>"
     rg = r"<c>.*<\/c>"
     for match in re.findall(rg, text):
         text = text.replace(match, "")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      • 2020-06-08
      • 1970-01-01
      • 2019-10-29
      • 1970-01-01
      • 2020-09-17
      • 2015-11-17
      相关资源
      最近更新 更多