How best to write this if-else?

Harry George hgg9140 at cola.ca.boeing.com
Mon Apr 23 09:46:12 EDT 2001


Despite the rococco flair of some of the answers given so far, I think
we do need an perlish idiom for this situation, where matching returns
a "true" value if successful.  Further, I think perl has a better
idiom for getting at the resulting matches.

That's one reason I wrote pyperl
(so named before Zope's effort -- I'll have to change mine I guess.).
See "pyperl" at:

  http://www.seanet.com/~hgg9140/comp/index.html

This allows the perlish idiom:

if p.m(regexpr_here,data_string_here):
    prematch=p.PREMATCH
    match=p.MATCH
    postmatch=p.POSTMATCH
    group1=p.S1    # S = $
    ....

[In fact, that is just about my only use of (my) pyperl these days --
I've converted mentally to python-isms for other tasks.]

It would be helpful if the "re" package would support this idiom in
future releases.
  

Roy Smith <roy at panix.com> writes:

> I want to test a line to see if it matches any of a bunch of pre-compile 
> regexes.  I also want to capture the match objects.  What  really want to 
> write is something like this (pseudo-code):
> 
> e1 = re.compile ('...')
> e2 = re.compile ('...')
> e3 = re.compile ('...')
> 
> line = file.readline()
> if (m = e1.match (line)):
>    text = m.group(1)
> elif (m = e2.match (line)):
>    text = m.group(1)
> elif (m = e3.match (line)):
>    text = m.group(1)
> 
> but I can't write it that way because python doesn't have assignment 
> operators.  Seems like I stuck with something like:
> 
> m = e1.match(line)
> if m:
>    text = m.group(1)
> else:
>    m = e2.match(line)
>    if m:
>       text = m.group(1)
>    else:
>      m = e3.match(line)
>       if m:
>         text = m.group(1)
> 
> but the best word I can think to describe that style of coding is "silly".  
> Is there really no more straight-forward way to do what I want?

-- 
Harry George                E-mail:  harry.g.george at boeing.com
The Boeing Company          Renton:  (425) 237-6915
P. O. Box 3707  02-CA       Everett: (425) 266-3868
Seattle, WA 98124-2207      Page:    (425) 631-8803  



More information about the Python-list mailing list