Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top