2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by pythonnoobie
0

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 :)

Edited by JeoSaurus: added test output!

0

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?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.