packing things back to regular expression

MRAB google at mrabarnett.plus.com
Thu Feb 21 15:13:13 EST 2008


On Feb 20, 7:36 pm, Amit Gupta <emaila... at gmail.com> wrote:
> Before I read the message: I screwed up.
>
> Let me write again
>
> >> x = re.compile("CL(?P<name1>[a-z]+)")
>
> # group name "name1" is attached to the match of lowercase string of
> alphabet
> # Now I have a dictionary saying {"name1", "iamgood"}
> # I would like a function, that takes x and my dictionary and return
> "CLiamgood"
> # If my dictionary instead have {"name1", "123"}, it gives error on
> processingit
> #
> # In general, I have reg-expression where every non-trivial match has
> a group-name. I want to do the reverse of reg-exp match. The function
> can take reg-exp and replace the group-matches from dictionary
> # I hope, this make it clear.

If you want the string that matched the regex then you can use
group(0) (or just group()):

>>> x = re.compile("CL(?P<name1>[a-z]+)")
>>> m = x.search("something CLiamgood!something else")
>>> m.group()
'CLiamgood'



More information about the Python-list mailing list