-3
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 writing regular expressions through a tool, and then generate the python code. There are some situations where I need to use ' or " or """ to wrap the regular expression. I want to try/except the error. If the error is captured, then I can try another. But it didn't work. Any help?

Ravindra S
  • 6,302
  • 12
  • 70
  • 108
mlzboy
  • 14,343
  • 23
  • 76
  • 97
  • 1
    Please. Find a tutorial. Do all of the tutorial. This question indicates that you skipped some sections. – S.Lott Oct 11 '10 at 11:16

2 Answers2

0

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
  • 12,490
  • 3
  • 42
  • 53
0

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
  • 951,095
  • 183
  • 1,149
  • 1,285
  • 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 Oct 11 '10 at 07:09
  • @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 Oct 11 '10 at 08:03
  • 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 Oct 11 '10 at 10:55