KA01
KA01

Reputation: 4251

How to append and prepend HTML substrings into a matched string using regular expression in python?

I am trying to search through a string of text for words that start with '#' (hashtags) and append/prepend HTML <a>#link</a> link tags to the word. I have come up with the regexp below:

string = '#hello here are some #text'
return re.sub('^#\w*|(?<=\s)#\w*', '<a href="{{url_for("main.tag")}}">#\1</a>', string)

It returns:

<a href="{{url_for("main.tag")}}">#\x01</a> here is some <a href="{{url_for("main.tag")}}">#\x01</a>

There's just one small issue: it doesn't include the matched word. What needs to be done to the regex?

Upvotes: 2

Views: 172

Answers (1)

rock321987
rock321987

Reputation: 11042

You need to use

re.sub('(^#\w*|(?<=\s)#\w*)', r'<a href="{{url_for("main.tag")}}">\1</a>', string)

Reason

i) There were no capturing groups. Included one

ii) You can use raw string r literal as you are substituting for capturing group (or \\1 if you are not using r)

iii) No need of including # as it is already captured

Upvotes: 2

Related Questions