[ale] Python regex
JK
jknapka at kneuro.net
Sat Sep 9 15:46:08 EDT 2006
Christopher Fowler wrote:
> I'm in the process of converting a Perl module to a Python equivalent so
> it can be used in Python programs. I'm not exactly a pro with Python.
> I may need a bit of help.
>
> One thing I love about Perl is regular expression support.
> I'm not sure how I can do the same in Python. The issue here is that
> I connect to a master database to get a connection string for an
> organizational database. I now need to connect to that database.
> Below is the string that comes from the connect_string column:
>
> jdbc:mysql://127.0.0.1/AC_DEMO
>
> In Perl I might do the following to extract what I need:
>
> connection_string =~ m/mysql:\/\/(.+?)/\(.+?)$/;
> $host = $1
> $db = $2
>
> Can someone tell me how I can do the equivalent in Python?
http://docs.python.org/lib/module-re.html
Briefly:
data="Somewhere in this string is something I want."
import re
regex="some.*[Ii]"
match=re.search(regex,data)
print match.group(0)
# Prints "something I"
Further details in the referenced URL. You can, for example,
precompile REs for performance, start searching at a
particular location, etc. It is slightly more verbose
than Perl, but equally flexible (I believe the same
underlying RE lib is used in both cases).
-- JK
More information about the Ale
mailing list