[英]Pattern matching on regex matches
The official tutorial ( https://www.python.org/dev/peps/pep-0636/#adding-a-ui-matching-objects ) shows that you can use use objects with the new pattern matching syntax, so I wanted to use it with regex matches like this:官方教程( https://www.python.org/dev/peps/pep-0636/#adding-a-ui-matching-objects )显示您可以使用新的模式匹配语法使用对象,所以我想要将其与正则表达式匹配使用,如下所示:
import re
match re.match(r"^foo", "foobar"):
case re.Match(span=(start, end), match=match):
print(f"match: {match} ({start}-{end})")
case _:
print("no matches")
But the first case never executes, what am I doing wrong?但是第一个案例永远不会执行,我做错了什么?
Use a wrapper to wrap the args you want, or even if you just want a non-none match, you can do that here.使用包装器来包装您想要的 args,或者即使您只想要一个非无匹配项,您也可以在此处执行此操作。
import re
class MatchWrap:
__match_args__ = "string"
def __init__(self, string, match: None):
self.string = string
self.match = match
def wrap_match(match):
if match:
return MatchWrap(match.string, match)
else:
return None
match wrap_match(re.match(r"^foo", "foobar")):
case MatchWrap(string="foobar") as obj:
print(f"match: {obj.match.string} ({obj.match.start}-{obj.match.end})")
case _:
print("no matches")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.