trying to match a string

oj ojeeves at gmail.com
Fri Jul 18 12:29:10 EDT 2008


>
> > Why not just use * instead of + like:
>
> > if re.search(r'^[^LRM]*$', var): # note: ^ outside [] is start of
> > string; $ means end of string
> >    print "Invalid"
>
> > This will *only* print invalid when there is a character other than L,
> > R, or M or a empty string.
>
> Sorry, forget the beginning and ending markers, I just tried it out, it
> doesn't work.
> use this instead:
>
> if re.search(r'[^LRM]*', var):
>    print "Invalid"

No, that's broken.

That searches for any number of invalid characters. Even 0, so it
ALWAYS matches, no matter what string you give it.

My regex worked in the first place, you're complicating it needlessly.
The presence of one invalid character makes the string invalid, so why
not just search for one? Similarly, there's no need to stick in the
beginning and end markers - you're not trying to match the entire
string, just find part of it that is invalid.

However, I think the sets solution by Scott David Daniels is the most
elegant method put forward.



More information about the Python-list mailing list