Newbie regex question.

Omri Schwarz ocscwar at h-after-ocsc.mit.edu
Wed Mar 13 16:47:00 EST 2002


Omri Schwarz <ocscwar at h-after-ocsc.mit.edu> writes:

> "Sean 'Shaleh' Perry" <shalehperry at attbi.com> writes:
> 
> > On 13-Mar-2002 Omri Schwarz wrote:
> > > 
> > > I have a regex = re.compile('yadda (widget1) (widget2) yadda')
> > > and want to search a string I know to have multiple 
> > > instances of this regex. I'm a tad confused by
> > > the RE Howto, so I'd like to ask, how do I properly 
> > > get a for loop to access the widget1 and widget2 
> > > strings of each instance?
> > > 
> > > for instance in regex.search(string).groups() 
> > > seems to be the right thing, but isn't working.
> > > 
> > 
> > >>> import re
> > >>> s= 'yadda widget1 widget2 yadda'
> > >>> regex = re.compile('yadda (widget1) (widget2) yadda')
> > >>> for match in regex.search(s).groups(): print match
> > ... 
> > widget1
> > widget2
> > 
> > This works here.  Although I would strongly caution you to do:
> > 
> > re_match = regex.search(s)
> > if re_match != None ......
> > 
> > just in case the regex fails.
> 
> What I was trying to get was 
> widget1 of instance 1
> widget2 of instance 1
> widget1 of instance 2
> widget2 of instance 2

And a web search shows I should have gone for
findall().

Pardon me while I put on a paper bag.

-- 
Omri Schwarz --- ocscwar at mit.edu ('h' before war) 
Timeless wisdom of biomedical engineering: "Noise is principally
due to the presence of the patient." -- R.F. Farr



More information about the Python-list mailing list