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? http://www.regular-expressions.info/python.html

Something like this?

#!/usr/bin/python

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 
APPsd222
APPxx333


-> python test.py 
<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=\"http://python.com=\\1\">\\1</a>", str)

Sample input 1:

Input File contains APPdd34

Output File contains <a href="http://python.com=APPdd34"> APPdd34</a>

Sample input 2:

Input File contains <a href="http://python.com=APPdd34"> APPdd34</a>

Output File contains <a href="http://python.com=<a href="http://python.com=APPdd34"> APPdd34</a>"> <a href="http://python.com=APPdd34"> APPdd34</a></a>

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

How can I rectify this problem?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.