Regex Replace for all to display as hyperlink


I need to find a pattern of kind APP[a-z][a-z][0-9][0-9][0-9] in the body of HTML and then replace them with hyperlinks.

I am using Beautiful Soup to replace as I am dealing with HTML content.

For Eg:
APPsd222 to APPsd222

APPfd333 to APPsd333

If you are not aware about Beautiful Soup, please tell me how to do for a String?


Would re.sub work for what you're doing?

Something like this?


import re
import fileinput

for line in fileinput.input("test.txt"):
    print re.sub("(APP[a-z]{2}[0-9]{3})", "<a href=\"\\1\">\\1</a>", line)

Here's a test run:

-> cat test.txt 

-> python 
<a href="APPsd222">APPsd222</a>

<a href="APPxx333">APPxx333</a>

I hope this helps! I'm also a python noob :)


The regex does the job. But I am facing a problem here. It also replaces the occurrences within <a href tag..

I am facing a problem as described below

modified_contents = re.sub("([^http://*/s]APP[a-z]{2}[0-9]{2})", "<a href=\"\\1\">\\1</a>", str)

Sample input 1:

Input File contains APPdd34

Output File contains <a href=""> APPdd34</a>

Sample input 2:

Input File contains <a href=""> APPdd34</a>

Output File contains <a href="<a href=""> APPdd34</a>"> <a href=""> APPdd34</a></a>

Desired Output File 2 is same as Sample Input File 2.

How can I rectify this problem?

This article has been dead for over six months: Start a new discussion instead
Start New Discussion
View similar articles that have also been tagged: