【问题标题】:RegEx for replacing all groups with one rowRegEx 用一行替换所有组
【发布时间】:2019-06-09 20:30:25
【问题描述】:

例如,我有这个字符串:

<ul><li><ahref="http://test.com">sometext</a></li></ul>

我想要这个输出:

<ul><li>[URL href="http://test.com"]sometext[/URL]</li></ul>

所以我创建了这个正则表达式,匹配&lt;ahref - 第一组,"&gt; - 第二组和&lt;/a&gt; - 第三组,将它们替换为[URL 用于第一组,"] 用于第二组和第三组[/URL]

pattern = r'(<a ?href).+(">).+(<\/a>)'

它匹配组,但现在我不知道如何替换它们。

【问题讨论】:

  • 不只是一个字符串,还是html文件?
  • 你试过re.sub
  • @RomanPerekhrest 只为这种情况寻找解决方案:))
  • @Xosrov 我尝试使用re.sub,但它取代了我整个比赛,而不仅仅是组
  • @MorganFreeFarm,如果它是用于 html 文件 - 我会推荐一种更强大的方法

标签: python regex python-3.x regex-group regex-greedy


【解决方案1】:

在这里,我们将使用 4 个捕获组捕获我们希望替换的内容,表达式类似于:

(<ul><li>)<a\s+href=\"(.+?)\">(.+?)<\/a>(<\/li><\/ul>)

Demo 1

对于缺少的空间,我们只需使用:

(<ul><li>)<ahref=\"(.+?)\">(.+?)<\/a>(<\/li><\/ul>)

Demo 2

如果我们可能同时拥有这两个实例,我们将使用捕获或非捕获组添加一个可选空间组:

(<ul><li>)<a(\s+)?href=\"(.+?)\">(.+?)<\/a>(<\/li><\/ul>)

Demo 3

测试

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

import re

regex = r"(<ul><li>)<a\s+href=\"(.+?)\">(.+?)<\/a>(<\/li><\/ul>)"

test_str = "<ul><li><a href=\"http://test.com\">sometext</a></li></ul>
"

subst = "\\1[URL href=\"\\2\"]\\3[/URL]\\4"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

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

正则表达式电路

jex.im 可视化正则表达式:

【讨论】:

  • 所以..你替换除了组之外的所有东西?
  • 谢谢!但我很好奇,有没有办法说“用这个字符串的这个匹配替换第 1 组”
【解决方案2】:
import re
text = "<ul><li><ahref=\"http://test.com\">sometext</a></li></ul>"
pattern = r'(<a ?href).+(">).+(<\/a>)'
url = re.findall('".*"', text)[0]
value = re.findall('>\w+<', text)[0][1:-1]
new_text = re.sub(pattern, '[URL href=' + url + "]" + value + '[/URL]', text)
print(new_text)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多