Здесь мы собираем то, что хотим заменить, используя 4 группы захвата, с выражением, похожим на:
(<ul><li>)<a\s+href=\"(.+?)\">(.+?)<\/a>(<\/li><\/ul>)
Для пропущенного места мы просто использовали бы:
(<ul><li>)<ahref=\"(.+?)\">(.+?)<\/a>(<\/li><\/ul>)
Если бы у нас были оба экземпляра, мы добавили бы необязательную группу пробелов, используя группу захвата или отсутствия захвата:
(<ul><li>)<a(\s+)?href=\"(.+?)\">(.+?)<\/a>(<\/li><\/ul>)
Test
# 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.
RegEx Circuit
jex.im визуализирует регулярные выражения:
![enter image description here](https://i.stack.imgur.com/QYZqH.png)