【问题标题】:Python exceptions and regex [closed]Python异常和正则表达式[关闭]
【发布时间】:2016-03-17 22:24:19
【问题描述】:

我有一个表达式用于在代码中引发异常,但允许此表达式的一种情况除外:

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 中做到这一点?

【问题讨论】:

  • 你的代码看起来很合理......你能发布一个简单的独立示例来演示你遇到问题的行为吗?

标签: python regex python-3.x search


【解决方案1】:

你可以这样做。用wrap_search() 包裹每个re.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 ))

【讨论】:

    【解决方案2】:

    您可以使用Warningclause 而不是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 中定义许多异常并编写一些自己的异常。

    【讨论】:

    • 过于嵌套和混乱。
    【解决方案3】:

    使用断言

    你的代码变成了

    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

    【讨论】:

    • 虽然这是有效的,有效的,但断言主要用于调试(例如,测试一个值是否在运行程序的某个时刻以某种方式出现),而不是实际的错误 -投掷。
    • 你是对的,因为它们可以被禁用。尽管 OP 没有指定是否用于调试,但代码似乎验证了用户输入。断言不是最好的选择。
    • 我也想要相反的情况——在所有情况下都断言异常,除非 searchexp.group(1) == 'tag'。这将如何运作?
    • 条件为False时会发生异常,所以这个例子会引发除'tag'之外的所有值的异常。 (但如果你想反转它,只需将== 更改为!=)。
    猜你喜欢
    • 2015-01-24
    • 2015-10-22
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 2012-12-16
    • 2013-10-28
    • 2020-04-22
    • 1970-01-01
    相关资源
    最近更新 更多