trying to match a string
Andrew Freeman
alif016 at gmail.com
Fri Jul 18 22:04:36 EDT 2008
oj wrote:
>>> 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.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
I see your point after rereading the question, he only wants to match L
R and M
let me revise it please:
To show if valid:
if re.search(r'^[LRM]*$', 'LM'):
print 'Valid'
To show if invalid,
if re.search(r'^[^LRM]*$', '0'):
print 'Inalid'
Example session:
>>> import re
>>> def match(var):
>>> if re.search(r'^[LRM]*$', var):
....... print 'Valid'
....... else:
....... print 'Invalid'
>>>
>>> eg = 'LRLRLRLRLM'
>>> match(eg)
Valid
>>> fg = 'LRLRLRNL'
>>> match(fg)
Invalid
--
Andrew
More information about the Python-list
mailing list