Remove character from backrefrence after using re.sub

Viewed 41

I have a string with a list of usernames mentioned for instance:

s = '@romeo went to @juliet and said hi, I'm @romeo'

I want to replace that username patter with links to user profile which should become <a href="/u/username">@username</a> I am now able to replace the patterns, however, I cannot seem to get rid of the @ in the href with using backreferences.

print(re.sub(r"(^|[^@\w])@(\w{1,31})", r'<a href="/u/\g<0>">\g<0></a>', s))

That right now prints:

<a href="/u/@romeo">@romeo</a> went to<a href="/u/ @juliet"> @juliet</a> and said hi, Im<a href="/u/ @romeo"> @romeo</a>

Which now you can see the extra space and @ I cannot seem to get rid of that after using the regex

1 Answers

You need to use

print(re.sub(r"\B(?<!@)@(\w{1,31})", r'<a href="/u/\1">\g<0></a>', s))

See the Python demo and the regex demo.

Regex

  • \B@ - @ char either at the start of string, or when immediately preceded with a non-word char
  • (?<!@) - the preceding @ should not be immediately preceded with @
  • (\w{1,31}) - Capturing group 1 (\1): one to thirty-one word chars.

The \1 in r'<a href="/u/\1">\g<0></a>' stands for the Group 1 value. \g<0> stands for the whole match.

Related