[Tutor] Regexp result

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Jan 21 18:21:48 EST 2004



On Wed, 21 Jan 2004, Helge Aksdal wrote:

> Is there anyway that i can put regexp results into strings?
> In Perl i use qr for that operation:
>
> [...]
> qr '(\w\w\w)\s(\d+?)\s(\d\d:\d\d:\d\d)',
> q  '($month, $day, $time) =3D ($1, $2, $3)',
> [...]
>
> Hope this was clear enough.


Hi Helge,


Ok, the Perl documentation from:

    perldoc perlop

says:

"""
       qr/STRING/imosx
               This operator quotes (and possibly compiles) its
               STRING as a regular expression.  STRING is inter=AD
               polated the same way as PATTERN in "m/PATTERN/".
"""


The closest equivalent to this 'qr' operator in Python is the re.compile()
function:

    http://www.python.org/doc/lib/node106.html#l2h-831



In Python, regular expressions are full-fledged objects, so you may want
to quickly browse through:

    http://www.python.org/doc/lib/module-re.html

Much of the functionality in Python's regular expressions lives in the
library, and not directly in the language, so the documentation on regular
expressions is in the Standard Library docs.



Here's example use of regular expressions:

###
>>> sample_text =3D "this is a test"
>>> pattern =3D re.compile(r"(\w+)\s*(\w+)\s*(\w+)\s*(\w+)")
>>> pattern.search(sample_text).groups()
('this', 'is', 'a', 'test')
###



A.M. Kuchling's Python Regex HOWTO should also help you transition your
Perl regular expression knowledge into Python:

    http://www.amk.ca/python/howto/regex/



I hope this helps!




More information about the Tutor mailing list