用于用一行替换所有组的正则表达式

RegEx for replacing all groups with one row

例如,我有这个字符串:

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

我想要这个输出:

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

所以我创建了这个正则表达式,以匹配 <ahref - 第一组,"> - 第二组和 </a> - 第三组,用 [URL 替换它们第一组,第二组"],第三组[/URL]

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

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

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

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

Demo 1

对于缺少 space,我们将简单地使用:

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

Demo 2

如果我们可能有两个实例,我们将使用捕获或 non-capturing 组添加一个可选的 space 组:

(<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 可视化正则表达式:

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)