tags:

views:

49

answers:

2
try:
    pattern=r'<tr><td><a href='(?P<link>[\s\S]*?)'[\s\S]*?><img src='(?P<img>[\s\S]*?)'     width='130' height='130'[\s\S]*?/></a></td>'
except:
    try:
        pattern=r"<tr><td><a href='(?P<link>[\s\S]*?)'[\s\S]*?><img src='(?P<img>[\s\S]*?)' width='130' height='130'[\s\S]*?/></a></td>"
    except:
        pattern=r"""<tr><td><a href='(?P<link>[\s\S]*?)'[\s\S]*?><img src='(?P<img>[\s\S]*?)' width='130' height='130'[\s\S]*?/></a></td>"""

i'm write some regual expression through tool,and then generate python code,there are some situation need use ' or " or """ to wrap the regualar expression,and i want to try except the error,if the error capture then i can try another ,but seems it didn't work,anyone could help me ,thanks

A: 

You need to escape your quotes inside the RE. In your first line, all the single quotes need to be escaped as \'.

Don't use a try block to fix your faulty RE. Just do it right the first time.

JoshD
A: 

The try/except statement in Python is used for errors that happen while your program is running. On the other hand, you are encountering errors that happen during compilation. In this case, try/except will not help you.

It looks like you would be best off always using """ to surround your regular expressions that contain different kinds of quotes. In Python, the only thing you can't put inside a triple-quoted string is a triple-quote.

Greg Hewgill
for an instance:a="""aaa"""",it will not works too,there there some way to dynamic compile the code and try catch the error and try another one?
mlzboy
@mlzboy: If you're generating this code from something else, then maybe escape all your embedded quotes. So `a="aaa\""` would be `aaa` followed by one `"`.
Greg Hewgill
i have process it in my way,it will cause error when use """ and the string endswith ",so at the string end i add a space,so it will not throw syntx error,after that,i do some escape, as you say above,thanks
mlzboy