trying to match a string

John S jstrickler at gmail.com
Fri Jul 18 18:28:42 CEST 2008


On Jul 18, 7:51 am, Andrew Freeman <alif... at gmail.com> wrote:
> Andrew Freeman wrote:
> > oj wrote:
> >> On Jul 18, 12:10 pm, John Machin <sjmac... at lexicon.net> wrote:
>
> >>> On Jul 18, 9:05 pm, oj <ojee... at gmail.com> wrote:
>
> >>>> On Jul 18, 11:33 am, arnimavidyar... at gmail.com wrote:
>
> >>>>> Hi,
> >>>>>         Hi,
> >>>>>         I am taking a string as an input from the user and it
> >>>>> should only
> >>>>> contain the chars:L , M or R
> >>>>>         I tried the folllowing in kodos but they are still not
> >>>>> perfect:
> >>>>>         [^A-K,^N-Q,^S-Z,^0-9]
> >>>>> [L][M][R]
> >>>>> [LRM]?L?[LRM]? etc but they do not exactly meet what I need.
> >>>>>         For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N'
> >>>>> .like that.
> >>>>>         regards,
> >>>>> SZ
> >>>>>         The string may or may not have all the three chars.
>
> >>>> With regular expressions, [^LRM] matches a character that isn't L, R
> >>>> or M. So:
> >>>>       import re
> >>>>       var = "LRLRLRLNR"
> >>>>       if re.search(r'[^LRM]', var):
> >>>>     print "Invalid"
>
> >>> Fails if var refers to the empty string.
>
> >> No it doesn't, it succeeds if var is an empty string. An empty string
> >> doesn't contain characters that are not L, R or M.
>
> >> The OP doesn't specify whether an empty string is valid or not. My
> >> interpretation was that an empty string would be valid.
>
> > 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"

This won't work -- every string in the universe contains 0 or more
characters which are not 'L', 'R', or 'M'. That is, the regular
expression X* could match the empty string, which can be found in all
strings.



More information about the Python-list mailing list