何かが正規表現に一致するかどうかを確認したい場合は、最初のグループを出力します..
import re
match = re.match("(\d+)g", "123g")
if match is not None:
print match.group(1)
これは完全に衒学的ですが、中間match
変数は少し面倒です..
Perl などの言語は、新しい$1
..$9
マッチ グループの変数を作成することでこれを行います。
if($blah ~= /(\d+)g/){
print $1
}
with re_context.match('^blah', s) as match:
if match:
...
else:
...
..これは興味深いアイデアだと思ったので、簡単な実装を書きました。
#!/usr/bin/env python2.6
import re
class SRE_Match_Wrapper:
def __init__(self, match):
self.match = match
def __exit__(self, type, value, tb):
pass
def __enter__(self):
return self.match
def __getattr__(self, name):
if name == "__exit__":
return self.__exit__
elif name == "__enter__":
return self.__name__
else:
return getattr(self.match, name)
def rematch(pattern, inp):
matcher = re.compile(pattern)
x = SRE_Match_Wrapper(matcher.match(inp))
return x
return match
if __name__ == '__main__':
# Example:
with rematch("(\d+)g", "123g") as m:
if m:
print(m.group(1))
with rematch("(\d+)g", "123") as m:
if m:
print(m.group(1))
(この機能は、理論的にはオブジェクトにパッチすることができ_sre.SRE_Match
ます)
一致するものがない場合、ステートメントのコード ブロックの実行をスキップできると便利ですwith
。これにより、これが簡素化されます。
with rematch("(\d+)g", "123") as m:
print(m.group(1)) # only executed if the match occurred
..しかし、これはPEP 343から推測できることに基づいて不可能に思えます
何か案は?私が言ったように、これは本当に些細な煩わしさであり、ほとんどコードゴルフのようです..