Regular Expressions?

S

soheil2.rm

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?

thanks a lot
 
D

Diez B. Roggisch

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)
 
D

David M. Cooke

Diez B. Roggisch said:
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)

I'd suggest using re.escape() to make sure there's no nasty surprises
inside of x and y:

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top