Regex

Chris Rebert clp2 at rebertia.com
Wed Oct 21 02:32:11 CEST 2009


> On Tue, Oct 20, 2009 at 8:06 PM, Steven D'Aprano
> <steven at remove.this.cybersource.com.au> wrote:
>> On Tue, 20 Oct 2009 16:20:14 -0700, Chris Rebert wrote:
>> > 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.*
>>
>> Or just use the glob and fnmatch modules.
>
On Tue, Oct 20, 2009 at 5:23 PM, Someone Something <fordhaivat at gmail.com> wrote:
> how can I implement this in python?

Please don't top-post.

If you only need to check whether a string matches a pattern or not:

if fnmatch.fnmatch(string_to_check, search_query_with_wildcards):
    do_whatever()

For more complicated stuff, there's fnmatch.translate(), which can
generate the equivalent regular expression.
http://docs.python.org/library/fnmatch.html#fnmatch.translate

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



More information about the Python-list mailing list