Python异常和正则表达式

时间:2016-03-17 22:24:20

标签: python regex python-3.x search

我有一个表达式,我用来在代码中引发异常,除了允许这个表达式的一种情况:

searchexp = re.search( r'^exp1=.*, exp2=(.*),.*', line )

我希望在遇到这种情况时引发异常,除非有一种情况我希望它打印警告

elif searchexp: 
  if searchexp.group(1) == 'tag'): 
    print("-w- just a warning that its a tag")
  else:
    raise Exception("-E- This is illegal to do")

简单的英文

if (searchexp)
  raise an Exception except if searchexp.group(1) == 'tag'

我如何在python中执行此操作?

3 个答案:

答案 0 :(得分:1)

你可以这样做。使用re.search()将每个wrap_search()换行。这将检查返回的匹配。

import warnings

def wrap_search(match):
    if not match:
        return

    if match.group(1) == "tag":
        warnings.warn("-w- just a warning that its a tag")
    else:
        raise Exception("-E- This is illegal to do")

    return match

searchexp = wrap_search(re.search( r'^exp1=.*, exp2=(.*),.*', line ))

答案 1 :(得分:0)

您可以使用Warning子句定义此警告,而不是Exception子句,因此您可以引发Warning并稍后捕获它,然后根据需要使用它。

示例:

try:
    try:
        # this code is supposed to fail with warning
    except Exception, e:
        raise Warning('my warning is here: {e}'.format(e=str(e))
    try:
        # this is another code supposed to fail with exception
    except Exception, e:
        raise 
except Warning, e:
    print ('My Warning was '+ str(e))
except Exception:
    raise Exception('write your exception here')

当然,你可以在python中定义很多异常并编写一些自己的异常。

答案 2 :(得分:0)

使用断言

您的代码变为

assert searchexp.group(1) == 'tag', "-E- This is illegal to do"

请参阅https://docs.python.org/2/reference/simple_stmts.html?highlight=assert#grammar-token-assert_stmt