regex that is equivalent to perl's syntax
Tim Chase
python.list at tim.thechases.com
Mon Nov 12 10:51:20 EST 2007
> does python's re library have a similar capability of the perls
> regular expression to
> search for pattern that appears a variable number of times within the
> lower and upper bounds given? For example, what is the python's
> equivalent to the following perl's search string?
> m/^\S{1,8}\.\S{0,3}/
> which seeks to find all strings with 8 characters followed by a dot
> and then three more characters as in filename.txt
>
> Actually, i need to find a pattern such as ABCDXLMNO with the
> character X
> repeated 5 to 8 times.
You're interested in the "re" library, documented here[1] which,
astonishingly, is the first result when I google for
python re library
In your particular case, the syntax is identical to perl
regexps[2] (the 2nd hit Google returns with the above query)
import re
r1 = re.compile(r'\S{1,8}\.\S{0,3}')
r2 = re.compile(r'ABCDX{5,8}LMNO')
# use r1/r2 for matching, substitution, taking over the world
Note the use of "raw" strings (doesn't matter so much in the 2nd
version, as there's nothing escaped), as suggested in the docs.
-tkc
[1] http://docs.python.org/lib/module-re.html
[2] http://docs.python.org/lib/re-syntax.html
More information about the Python-list
mailing list