En Fri, 02 May 2008 15:51:42 -0300, Oltmans <[EMAIL PROTECTED]> escribió:

Hi,

I'm new to Python (and admittedly not a very good programmer) and I've
come across a scenario where I've to search and replace text in a
file.

For the sake of an example, I'm searching for every occurence of the
text
[[http://www.hotmail.com -> Hotmail]]

I've to replace it with
[http://www.hotmail.com Hotmail]

I've come up with following scheme
p=re.compile(r'\[\[')
q=re.compile(r'->')

p.sub('[',txt)
q.sub('\b',txt)

Is it a constant text? Then use the replace method of string objects: no re is needed.

text = "This is [[http://www.hotmail.com -> Hotmail]] some text"
print text.replace("[[http://www.hotmail.com -> Hotmail]]", "[http://www.hotmail.com Hotmail]")
output: This is [http://www.hotmail.com Hotmail] some text

Or, do you want to find '[[' followed by some word followed by ' -> ' followed by another word followed by ']]'?

r = re.compile(r'\[\[(.+?)\s*->\s*(.+?)\]\]')
print r.sub(r'[\1 \2]', text)
(same output as above)

() in the regular expression indicate groups, that you can reference as \1 \2 in the replacement string.

--
Gabriel Genellina

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to