When not to use an RE -- an example
Chris
password.april03.20.netman at spamgourmet.com
Mon Apr 21 22:17:05 EDT 2003
What's wrong with:
def findrepeat(s): return len(s) > 1 and not filter(lambda x: x !=
s[0], s)
Chris
"John Machin" <sjmachin at lexicon.net> wrote in message
news:c76ff6fc.0304191459.2adf73a at posting.google.com...
> I needed a check for strings consisting of repeated characters -- like
> when users type "ZZZZZZZ" instead of "UNKNOWN" into a database field.
> After implementing the obvious overlapping-substring comparison, I got
> to thinking how this could be done with REs. The following resulted:
>
> import re
> repeats1 = re.compile(r"^(?:(.)(?=\1))+\1\Z", re.DOTALL).match
> def repeats2(s):
> return len(s) > 1 and s[1:] == s[:-1]
> for testvalue, expected in zip(
> ['','x','xx','xxx','xxxxxx','xy','xxy','xyy','\n\n\n','aaa\n'],
> [0, 0, 1, 1, 1, 0, 0, 0, 1, 0 ]):
> print repr(testvalue), not not repeats1(testvalue),
> repeats2(testvalue), expected
>
> Pergly/phugly, eh? Note the effort required to ensure the newline
> cases worked.
More information about the Python-list
mailing list