On Wed, 30 Apr 2008 17:12:15 +1000, Kam-Hung Soh <[EMAIL PROTECTED]> wrote:

On Wed, 30 Apr 2008 15:27:36 +1000, Raymond <[EMAIL PROTECTED]> 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>
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to