pattern match
Dang Griffith
dmgriffith at tasc.com
Wed Apr 23 11:45:02 EDT 2003
Mitch MF Cummstain wrote:
> I just started using python and I need help with a
> pattern match.
>
> m = re.match("(.{30})(word)(.{30})",paragraph);
>
> I need to match 30 characters on each side of word. The problem word
> is getting treated as a string not a variable like I need it to. How
> can I make it treat word as a variable ?
I'm using 3 instead of 30, but I think you'll get the idea.
>>> import re
>>> paragraph = "abcdefghijklmnopqrstuvwxyz"
>>> word = "lmn"
>>> pat = "(.{3})(%s)(.{3})" % word
>>> # or, pat = "(.{3})(" + word + ")(.{3})"
>>> m = re.search(pat, paragraph)
>>> m.groups()
('ijk', 'lmn', 'opq')
Something to keep in mind is that re.match only matches at the beginning
of the string. You might consider using re.search instead, as I did
above. It also returns match objects you can play with.
--dang
More information about the Python-list
mailing list