The reason your template doesn’t work is here: (?<=\((.*)\)\[) , Because the Python re-module doesn’t allow you to search for variable lengths.
You can get what you want in a more convenient way using the new Python regular expression module (since the re module has several features in comparison).
Example: (?|(?<txt>(?<url>(?:ht|f)tps?://\S+(?<=\P{P})))|\(([^)]+)\)\[(\g<url>)\])
online demo
more details:
(?|
This template uses the reset function branch (?|...|...|...) , which allows you to save the names of capture groups (or numbers) in rotation. In the template, since the group ?<txt> opened first in the first interleave, the first group in the second member will have the same name automatically. Same for the group ?<url> .
\g<url> is a reference to a named subpattern ?<url> (for example, an alias, so you don't have to rewrite it in the second member.)
(?<=\P{P}) checks to see if the last character of the URL is not a punctuation character (useful, for example, to avoid the closing square bracket). (I'm not sure about the syntax, it could be \P{Punct} )
source share