Regex

Chris Rebert clp2 at rebertia.com
Tue Oct 20 19:20:14 EDT 2009


On Tue, Oct 20, 2009 at 3:16 PM, Someone Something <fordhaivat at gmail.com> wrote:
> I'm trying to write a program that needs reg expressions in the following
> way. If the user types in "*something*" that means that the asterixes can be
> replaced by any string of letters. I haven't been able to find any reg
> expression tutorials that I can understand. Help?

Sounds like you only need globbing
(http://en.wikipedia.org/wiki/Glob_%28programming%29) as opposed to
full regexes.
Simple wildcard globbing can be trivially done by replacing the *s in
the string with ".*", like so:

*something* ===> .*something.*

A period matches any single character (except newline), and an
asterisk matches zero or more of whatever came directly before it.
Thus, ".*" matches anything (including nothing -- the empty string),
barring newlines.

Assuming there are no special characters ( ^ $ [ ] . * {} () \ ) in
the original pattern string or you've properly escaped them with
backslashes, you can then feed this processed string directly into the
regex engine and get your desired match.

If you have the cash for a dead-tree book, "Mastering Regular
Expressions" is quite serviceable and I've heard good things about
"Regular Expressions Cookbook".

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list