Re: [Tutor] use of variables in re.sub

2013-02-14 Thread Oscar Benjamin
On 14 February 2013 12:57, Eva Bofias  wrote:
> Helo,

Hi,

> I need to do a substitution in a regular expression that depends on a
> variable. To simplify I want to be able to do this substitution:
>
> text2='XX. AA YY. DD'
> re.sub(ur"\. (AA|BB|ÇÇ","(.) \g<1>",text2)

There is a missing bracket in that expression. did you mean ur"\. (AA|BB|ÇÇ)"?

> this would give as a result:
> 'XX(.) AA YY. DD'
> Which is exactly what I want.
>
> But when I try to substitute AA|BB|CC for a variable I do not know how to
> make it work.

How about this?

>>> import re
>>> text2='XX. AA YY. DD'
>>> re.sub(ur"\. (AA|BB|ÇÇ)",r"(.) \g<1>",text2)  # ¡Note the r"" raw string!
'XX(.) AA YY. DD'


Or have I misunderstood?


Oscar
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] use of variables in re.sub

2013-02-14 Thread Eva Bofias
Helo,

I need to do a substitution in a regular expression that depends on a
variable. To simplify I want to be able to do this substitution:

text2='XX. AA YY. DD'
re.sub(ur"\. (AA|BB|ÇÇ","(.) \g<1>",text2)

this would give as a result:
'XX(.) AA YY. DD'
Which is exactly what I want.

But when I try to substitute AA|BB|CC for a variable I do not know how to
make it work.
I wanted to use re.compile. I tryed:

NP= u"AA|BB|ÇÇ"
reNP=re.compile(ur'%s'%NP)

But if I try:

reNP.match(text2)

And I do not know how to use the variables in there. Should I use
re.compile or is there something else that I should be using

Thank you

Eva Bofias
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor