问题
Is it possible to do something like the following Perl code in Python? From what I can tell the answer is no, but I figured I'd double check.
The Perl code I want to replicate in Python:
#!/usr/bin/perl
my $line = "hello1234world";
if($line=~/hello(.*)world/) {
print($1);
}
#prints 1234
The following is the closest stylistically I can think off, but when running I (obviously) get the following error:
import re
line = "hello1234world"
if matchObj = re.match(r'hello(.*)world',line):
print(matchObj.group(1))
#error: if matchObj = re.match(r'hello(.*)world',line):
#error: ^
#error: SyntaxError: invalid syntax
The following is the best working code I can come up with:
import re
line = "hello1234world"
matchObj = re.match(r'hello(.*)world',line)
if matchObj:
print(matchObj.group(1))
#prints 1234
I'd really like to avoid a separate line for the variable declaration and if statement if possible.
回答1:
Can just print the (assumed) capture and use exceptions to handle the case when group
method is called on None
, returned when there isn't a match. If there is indeed nothing to do when the match fails it's one line via With Statement Context Manager (3.4+)
from contextlib import suppress
with suppress(Exception):
print( re.match(r'hello(.*)world', line).group(1) )
To avoid ignoring exceptions that almost surely shouldn't be ignored here, like SystemExit
and KeyboardInterrupt
, use
with suppress(BaseException):
...
This is now rather compact, as asked for, and it behaves as desired. Using exceptions merely to shorten code could be considered misguided though, but perhaps there'd be further uses of this.
As mentioned in comments, since 3.8 there is the Assignment Expression
if match := re.match(r'hello(.*)world', line):
print( match.group(1) )
which matches almost directly the motivating semantics. However, this newer feature has drawn some sensitive discussions, while using it to merely shorten code may confuse and mislead as it differs from an expected pythonic approach.
I'd like to add, that I'd suggest to not worry about a few extra lines of code, and specially to avoid emulating styles and program flow from other languages. There is a huge value in using styles and idioms native to the language at hand.
来源:https://stackoverflow.com/questions/64038216/python-use-regex-match-object-in-if-statement-and-then-access-capture-groups-lik