5

我想知道在python(3.2,如果相关的话)中是否有可能发生这样的事情。

with assign_match('(abc)(def)', 'abcdef') as (a, b):
    print(a, b)

行为在哪里:

  • 如果正则表达式匹配,则正则表达式组被分配到ab
    • 如果那里不匹配,它会抛出异常
  • 如果匹配None,它将完全绕过上下文

我的目标基本上是一种非常简洁的上下文行为方式。

我尝试制作以下上下文管理器:

import re

class assign_match(object):
    def __init__(self, regex, string):
        self.regex = regex
        self.string = string
    def __enter__(self):
        result = re.match(self.regex, self.string)
        if result is None:
            raise ValueError
        else:
            return result.groups()
    def __exit__(self, type, value, traceback):
        print(self, type, value, traceback) #testing purposes. not doing anything here.

with assign_match('(abc)(def)', 'abcdef') as (a, b):
    print(a, b) #prints abc def
with assign_match('(abc)g', 'abcdef') as (a, b): #raises ValueError
    print(a, b)

它实际上完全符合正则表达式匹配的情况,但是,如您所见,它会抛出ValueErrorif there's no match。有什么办法可以让它“跳”到退出序列?

谢谢!!

4

1 回答 1

4

啊! 也许在 SO 上解释它为我澄清了这个问题。我只是使用 if 语句而不是 with 语句。

def assign_match(regex, string):
    match = re.match(regex, string)
    if match is None:
        raise StopIteration
    else:
        yield match.groups()

for a in assign_match('(abc)(def)', 'abcdef'):
    print(a)

给出了我想要的行为。将其留在这里以防其他人想从中受益。(Mods,如果不相关,请随时删除等)

编辑:实际上,这个解决方案带有一个相当大的缺陷。我在 for 循环中执行此行为。所以这阻止了我做:

for string in lots_of_strings:
    for a in assign_match('(abc)(def)', string):
        do_my_work()
        continue # breaks out of this for loop instead of the parent
    other_work() # behavior i want to skip if the match is successful

因为 continue 现在打破了这个循环,而不是父 for 循环。如果有人有建议,我很想听听!

EDIT2:好吧,这次真的想通了。

from contextlib import contextmanager
import re

@contextmanager
def assign_match(regex, string):
    match = re.match(regex, string)
    if match:
        yield match.groups()

for i in range(3):
    with assign_match('(abc)(def)', 'abcdef') as a:
#    for a in assign_match('(abc)(def)', 'abcdef'):
        print(a)
        continue
    print(i)

很抱歉这个帖子 - 我发誓在我发帖之前我真的感觉很卡。:-) 希望其他人会觉得这很有趣!

于 2012-05-26T19:09:03.710 回答