sed to python: replace Q
Kam-Hung Soh
kamhung.soh at gmail.com
Wed Apr 30 03:12:15 EDT 2008
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))
>
> Is there a decent description of string.replace() somewhere?
>
> Raymond
Section 3.6.1 String Functions
--
Kam-Hung Soh <a href="http://kamhungsoh.com/blog">Software Salariman</a>
More information about the Python-list
mailing list