[perl-python] string pattern matching

Xah Lee xah at xahlee.org
Tue Feb 1 15:45:07 EST 2005


# -*- coding: utf-8 -*-
# Python

# Matching string patterns
#
# Sometimes you want to know if a string is of
# particular pattern.  Let's say in your website
# you have converted all images files from gif
# format to png format. Now you need to change the
# html code to use the .png files. So, essentially
# you want to replace strings of the form
#
# img src="*.gif"
# to
# img src="*.png"
#
# Python provides string pattern matching by the
# "re" module.  (String Pattern Matching is
# inanely known as Regular Expression (regex) in
# the computing industry. It is a misnomer and
# causes great unnecessary confusion.)


©import re
©
©text='''<img src="../Icons_dir/icon_sum.gif" width="32"
height="32">'''
©
©pattern = r'''src="([^"]+)\.gif"'''
©
©result = re.search(pattern, text)
©
©if result:
©     print 'yes'
©     print result.expand(r"\1") # the captured pattern
©else:
©     print 'no'

#-------------
# if re.search(pattern, text) does not match, then the result is
None. If it matches, an object is returned. One can then use methods
such as .groups(), .expand(), .split() ... to find the matched parts,
or a given replacement string, or split the text into multiple part
by the regex...

# regex is quite confusing for beginners, but
# isn't really difficult to understand. It comes
# with practice.

# see
# http://python.org/doc/lib/module-re.html
# for detail.

# i'll have to study more to make complet example. Try it yourself.

-----------------

# in perl, regex is its mainstay.
# very expressive with syntax, but not so in semantic,
# when compared to Python.

# for syntax variability, for example the following are all the same.

$text = "what ever is here to be matched";

if ( $text =~ ever) { print 'yes'} else {print "no"}
if ( $text =~ /ever/) { print 'yes'} else {print "no";}
if ( $text =~ m/ever/) { print 'yes'} else {print "no"}
if ( $text =~ m(ever)) { print 'yes'} else {print "no"}
if ( $text =~ m at ever@) { print 'yes'} else {print "no"}

# for detail of its much ado about nothing nature,
# see perldoc perlre

--------
this is perl-python a-day mailing list. To subscribe, see
http://xahlee.org/perl-python/python.html
Xah
  xah at xahlee.org
  http://xahlee.org/PageTwo_dir/more.html




More information about the Python-list mailing list