Python re.search assistance for Django

Question:

I need to replace part of an an html string via a Django custom template tag that I am customising.

The string in it’s raw format is as follows:

arg = "<a class='login-password-forget' tabindex='1' href='{% url 'account:pwdreset'%}'>Forgot your password?</a>"

I need to replace the {% url 'account:pwdreset'%} part with a url string using re.search().

The code that I written is clumsy and I would appreciate help with finding a better way of achieving the same.

url_string = re.search("{.*?}", arg)
url_string_inner = re.search("'(.+?)'", url_string.group())

add_html = SafeText(''.join([arg.split('{')[0], reverse(url_string_inner.group(1)), arg.split('}')[1]]))

!!UPDATE!!
The solution that I ran with is as follows:

    url_string = re.search("{.*?}", arg)
    url_string_inner = re.search("'(.+?)'", url_string.group())
    add_html = SafeText(''.join([arg.split('{')[0], reverse(url_string_inner.group(1)), arg.split('}')[1]]))

Thank you Fourth Bird for your help.

Asked By: CanDo

||

Answers:

If you only want to replace the the part with 'account:pwdreset' you could use re.sub with a capture group and use that group in the replacement between single quotes

'{%s*url '([^']*)'%}

Regex demo | Python demo

import re

pattern = r"'{%s*url '([^']*)'%}"
s = "<a class='login-password-forget' tabindex='1' href='{% url 'account:pwdreset'%}>Forgot your password?</a>"
print(re.sub(pattern, r"'1'", s))

Output

<a class='login-password-forget' tabindex='1' href=account:pwdreset>Forgot your password?</a>
Answered By: The fourth bird
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.