(如果这是重复的,我们深表歉意,但无法通过 google/搜索 $+
!)
我正在寻找与 Perl 的 $+
又名 $LAST_PAREN_MATCH
最接近/最好的等价物。
对于那些不了解 Perl 的人,它是这样描述的:
$LAST_PAREN_MATCH
$+ The text matched by the last bracket of the last successful search
pattern. This is useful if you don't know which one of a set of
alternative patterns matched.
也就是说,如果我有一个类似 (b)|(a)|(r)
的模式,那么 $+
将包含 b
, a
或 r
取决于匹配的子模式。
我拥有的最好的是
next((g for g in reversed(match.groups(None)) if g is not None),None)[0]
对于长期的 Perl 黑客来说,这似乎是一件简单的事情的大量代码。
(并不是说我不知道我可以将它包装在函数 last_paren_match(match)
:-)
最佳答案
Python 中可能没有等效项,但如果您使用分支重置 模式(?|...)
然后每个交替管道 |
在模式中将重置捕获变量的计数器。我很确定 Python 会支持它
在这个例子中,所有捕获组都保存在$1
中
use strict;
use warnings 'all';
use feature 'say';
'zax' =~ /(?|(b)|(a)|(r))/;
say $1;
输出
a
关于Python 相当于 Perl $+ aka $LAST_PAREN_MATCH,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42810217/