A better RE?

Fredrik Lundh fredrik at pythonware.com
Fri Mar 10 07:35:46 EST 2006


Eddie Corns wrote:


> >I want an re that matches strings like "21MAR06 31APR06 1236",
> >where the last part is day numbers (1-7), i.e it can contain
> >the numbers 1-7, in order, only one of each, and at least one
> >digit. I want it as three groups. I was thinking of
>
> Just a small point - what does "in order" mean here? if it means that eg 1362
> is not valid then you're stuck because it's context sensitive and hence not
> regular.
>
> I can't see how any of the fancy extensions could help here but maybe I'm
> just lacking insight.

import re

p = re.compile("(?=[1234567])(1?2?3?4?5?6?7?)$")

def test(s):
    m = p.match(s)
    print repr(s), "=>", m and m.groups() or "none"

test("")
test("1236")
test("1362")
test("12345678")

prints

'' => none
'1236' => ('1236',)
'1362' => none
'12345678' => none

</F>






More information about the Python-list mailing list