Regular Expressions?

Diez B. Roggisch deets_noospaam at web.de
Wed Feb 25 11:18:05 CET 2004


> I want to use a regular expression like the following:
> 
> "*[\s|\w]*" + x +"[\s|\w]*\" + y + "*[\s|\w]*\" + y + "*[\s|\w]*"
> 
> where x and y and varaiblae names and their value changes everytime.
> For some reason this gives me an Invalid Token error. Can I use
> variables in a regular Expression?

Sure. But what you wrote above is most probably syntactically wrong:

"*[\s|\w]*" + x +"[\s|\w]*\" + y + "*[\s|\w]*\" + y + "*[\s|\w]*"
                          ^^ 
You escape the d'qoutes, so that not the variable is inserted but instead
the text " + y + ". Then a [ starts, which denotes the beginning of a list
- a thing not supported right here. The same problem arises before the
second y.

This works for me:

"*[\s|\w]*" + x +"[\s|\w]*" + y + "*[\s|\w]*" + y + "*[\s|\w]*"

However, I suggest you use the %-operator in such cases:

"*[\s|\w]*%s[\s|\w]*%s*[\s|\w]*%s*[\s|\w]*" % (x, y, y)


-- 
Regards,

Diez B. Roggisch



More information about the Python-list mailing list