[Tutor] Regex in Python

Kent Johnson kent37 at tds.net
Fri Jul 28 04:48:41 CEST 2006


The Fulch wrote:
>
> Thanks for you help,
>
> Another question, is there a way of comparing two regexs?
>
> EG
>
> s1='st*r'
> s2='s*ar'
>
> r1=s1.replace('*','.*')
> r2=s2.replace('*','.*')
>
> re.match(r1,r2)?
>
That will do something, though I don't know if it is what you want. r1 
and r2 are both strings, so you can use one to search in the other. But 
what do you want it to do?

BTW re.match() and re.search() do different things, which one do you want?
>
> =============
>
> Also how do I use  <_sre.SRE_Match object at 0x00E3F6B0> in my program?
> If its a match, I want to be able to return 'true' or 1
>
You can probably just return the match object, if you test for it in an 
if statement it will test as true. If you really want a boolean value 
then say
  return re.search(...) is not None

Kent
>
> Mike
> >The Fulch wrote:
> > > Hi,
> > >
> > > Given two strings I need to determine weather or not one of the
> > > strings is a subset of the other string. In at least one of the
> > > strings there is a star "*" which can be any character or a null there
> > > is a maximum of one star per string.
> > >
> > > So basically I want the function to return true if you try to match
> > > st*r and star
> > > st*r and str
> > > sta*rshine and star
> > > st* and star
> > > st*r and stststar
> > > t*r and s*ar
> >I'm not sure how this is a match, can you clarify?
> > >
> > >
> > > I tried making a function which splits the input by "*" but don't
> > > really know how to continue after that. I have been trying to use reg
> > > ex, but with little success.
> >
> >If just one string has a match, you can change the * to .* and get a
> >regular expression to search for in the other string.
> >In [1]: import re
> >
> >In [2]: s1='st*r'
> >
> >In [3]: s2='star'
> >
> >In [4]: regex = s1.replace('*', '.*')
> >
> >If the search succeeds, it returns a match object:
> >In [5]: re.search(regex, s2)
> >Out[5]: <_sre.SRE_Match object at 0x00E3F6B0>
> >
> >If the search fails, it returns None:
> >In [6]: re.search(regex, 'foo')
> >
> >In [7]:
> >
> >Kent
> >
>




More information about the Tutor mailing list