John Machin wrote:
On Jul 19, 12:04 pm, Andrew Freeman <[EMAIL PROTECTED]> wrote:
To show if valid:

if re.search(r'^[LRM]*$', 'LM'):
    print 'Valid'


A couple of points:
(1) Instead of search(r'^blahblah', ...) use match(r'blahblah', ...)
(2) You need to choose your end-anchor correctly; your pattern is
permitting a newline at the end:

re.search(r'^[LRM]*$', 'LM\n')
<_sre.SRE_Match object at 0x00B9E528>
--
http://mail.python.org/mailman/listinfo/python-list
Thanks for your pointers, however have a question regarding the first:

>>> import re
>>> def my_match(var):    # my original
>>>     if re.search(r'^[LRM]*$', var):
>>>         print 'Valid'
>>>     else:
>>>         print 'invalid'
>>> def other_match(var):   # your suggestion, I believe
>>>     if re.search(r'[LRM]*$', var):
>>>         print 'Valid'
>>>     else:
>>>         print 'Invalid'
>>>
>>> eg = 'LRLRLRLRLM'
>>> fg = 'LRLRLRNL'
>>> my_match(eg)
Valid    # correct!
>>> my_match(fg)
Invaild  # correct!
>>>
>>> other_match(eg)
Valid # correct!
>>> other_match(fg)
Vaild     # INCORRECT, please explain

I believe other_match was your suggestion; to remove the ^
my_match is just a renamed version of my original function

Point 2:
Yes, I totally agree with you on point 2, let me try to combine my knowledge and make a satisfactory function.

>>> def final_match(var):
>>> if re.search(r'^[LRM]*\Z', var): # replace $ with \Z to limit newlines
...         print 'Valid'
...     else:
...         print 'Invalid'
>>>  final_match(eg)
Valid
>>> final_match(fg)
Invalid
>>> final_match(eg + '\n')
Invalid

So, in conclusion, is this function satisfactory?

def match(var):
   if re.search(r'^[LRM]*\Z', var):
       print 'Valid'
   else:
       print 'Invalid'
--
Andrew
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to