How do I find possible matches using regular expression?

John Machin sjmachin at lexicon.net
Thu Nov 23 05:20:06 EST 2006


Andy wrote:
> Hi there,
>
> 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 answer is: Using regular expressions doesn't seem like a good idea.
If you want to match against only one target, then
target.startswith(user_input) is, as already mentioned, just fine.
However if you have multiple targets, like a list of computer-language
keywords, or the similar problem of an IME for a language like Chinese,
then you can set up a prefix-tree dictionary so that you can search the
multiple target keywords in parallel. All you need to do is keep a
"finger" pointed at the node you have reached along the path; after
each input character, either the finger gets pointed at the next
relevant node (if the input character is valid) or you return/raise a
failure indication.

HTH,
John




More information about the Python-list mailing list