sed to python: replace Q

Kam-Hung Soh kamhung.soh at gmail.com
Thu May 1 02:00:33 EDT 2008


On Wed, 30 Apr 2008 17:12:15 +1000, Kam-Hung Soh <kamhung.soh at gmail.com>  
wrote:

> On Wed, 30 Apr 2008 15:27:36 +1000, Raymond <not-for-mail at sonic.net>  
> wrote:
>
>> For some reason I'm unable to grok Python's string.replace() function.
>> Just trying to parse a simple IP address, wrapped in square brackets,
>> from Postfix logs. In sed this is straightforward given:
>>
>> line = "date process text [ip] more text"
>>
>>   sed -e 's/^.*\[//' -e 's/].*$//'
>>
>> yet the following Python code does nothing:
>>
>>   line = line.replace('^.*\[', '', 1)
>>   line = line.replace('].*$', '')
>
> str.replace() doesn't support regular expressions.
>
> Try:
>
> import re
> p = re.compile("^.*\[")
> q = re.compile("].*$")
> q.sub('',p.sub('', line))
>

Another approach is to use the split() function in "re" module.

import re
re.split("[\[\]]", line)[1]

See http://docs.python.org/lib/node46.html

-- 
Kam-Hung Soh <a href="http://kamhungsoh.com/blog">Software Salariman</a>



More information about the Python-list mailing list