How do I find possible matches using regular expression?

Andy icetortoise at gmail.com
Thu Nov 23 13:53:54 CET 2006


The seems good to me, I'll try it out, thanks for the posting.


"Peter Otten 写道:
"
> Andy wrote:
>
> > I'm trying to do some predicting work over user input, here's my
> > question:
> >
> > for pattern r'match me', the string 'no' will definitely fail to match,
> > but 'ma' still has a chance if user keep on inputting characters after
> > 'ma', so how do I mark 'ma' as a possible match string?
>
> The following may or may not work in the real world:
>
> import re
>
> def parts(regex, flags=0):
>     candidates = []
>     for stop in reversed(range(1, len(regex)+1)):
>         partial = regex[:stop]
>         try:
>             r = re.compile(partial + "$", flags)
>         except re.error:
>             pass
>         else:
>             candidates.append(r)
>     candidates.reverse()
>     return candidates
>
> if __name__ == "__main__":
>     candidates = parts(r"[a-z]+\s*=\s*\d+", re.IGNORECASE)
>     def check(*args):
>         s = var.get()
>         for c in candidates:
>             m = c.match(s)
>             if m:
>                 entry.configure(foreground="#008000")
>                 break
>         else:
>             entry.configure(foreground="red")
>
>
>     import Tkinter as tk
>     root = tk.Tk()
>     var = tk.StringVar()
>     var.trace_variable("w", check)
>     entry = tk.Entry(textvariable=var)
>     entry.pack()
>     root.mainloop()
>
> The example lets you write an assignment of a numerical value, e. g
>
> meaning = 42
>
> and colours the text in green or red for legal/illegal entries.
> 
> Peter




More information about the Python-list mailing list