regular expression reverse match?

Emile van Sebille emile at fenx.com
Wed Oct 29 03:48:46 EST 2003


"Ron Adam" <radam2 at tampabay.rr.com> wrote in message
news:1jrupvoprk35v633ecb2lnlu5r1eu0sceb at 4ax.com...
> On Tue, 28 Oct 2003 20:09:38 -0800, "Emile van Sebille"
> <emile at fenx.com> wrote:
>
> >I'll assume you mean comething like:
> >
> >x = re.compile('abcd and a bunch of other stuff')
> >
> >>
> >> This is what i'm looking for:
> >>
> >> string  /  result
> >>   'a'  /  pass
> >> 'ab' /  pass
> >> 'abc'  / pass
> >> 'abd'  /  fail
> >> 'aaaa'  /  fail
> >> 'abcd and a bunch of other stuff and then some'  /  fail
> >>
> >> Is there a way to form a regular expression that will do this?
> >
> >for k,v in re._cache.items():
> >    if v == x:
> >        ss=k[0]
> >        break
> >
> >Then it's a normal:
> >
> >>>> re.match('a',ss)
> ><_sre.SRE_Match object at 0x009828E0>
> >>>> re.match('abd',ss)
> >>>>
> >
>
>
> Hi again Emile,
>
> I tried it and get an error.
> Here's my result.  Am I missing something?

See, I told you it wouldn't work  ;-)    I abused an implementation detail
that apparently doesn't exist on the version you've got.

[snip]

> New problem:    Is there a way to expand an re from:
>
> 'yes$'  to   'y$|ye$|yes$'
>
> and
>
> '(yes$)|(no$)' to  '(y$|ye$|yes$)|(n$|no$)'
>
> and
>
> '\d{30}$'  to  '\d{1}$|\d{2}$|\d{3}$|\d{4}$|\d{5}$|  .......'
>
>
> Other expressions that I might use would be:
>
> '\d{3}-\d{3}-d\{4}$'    to match a phone number
>

You'll probably want to build a validation routine.  Here's one quick idea:

import re

def oksofar(pattern, test, sample):
    teststr = "".join([test,sample[len(test):]])
    return not not re.match(pattern, teststr)

for p,t,s in [
  (r'^(\d{5})$', '123456', '56789'),
  (r'^([A-Z]{2}\d(2))$', 'AB4x', 'XY12'),
  (r'^(\d{5})-(\d{4})$', '55555-1234', '55555-1212')
             ]:
    print p,t,s,not not re.match(p, s)
    for ii in range(len(t)):
        print ii,t[:ii+1], oksofar(p, t[:ii+1], s)


HTH,

Emile van Sebille
emile at fenx.com






More information about the Python-list mailing list