相关疑难解决方法(0)

Python 在 if 语句中使用正则表达式匹配对象,然后访问像 Perl 这样的捕获组

是否可以在 Python 中执行类似以下 Perl 代码的操作?据我所知,答案是否定的,但我想我会仔细检查一下。

我想在 Python 中复制的 Perl 代码:

#!/usr/bin/perl

my $line = "hello1234world";

if($line=~/hello(.*)world/) {
  print($1);
}
#prints 1234    
Run Code Online (Sandbox Code Playgroud)

以下是我能想到的最接近的风格,但在运行时我(显然)收到以下错误:

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
Run Code Online (Sandbox Code Playgroud)

以下是我能想到的最好的工作代码:

import re
line = "hello1234world"

matchObj = re.match(r'hello(.*)world',line)

if matchObj:
    print(matchObj.group(1))
#prints 1234
Run Code Online (Sandbox Code Playgroud)

如果可能的话,我真的很想避免为变量声明和 if 语句单独一行。

python regex perl

3
推荐指数
1
解决办法
94
查看次数

标签 统计

perl ×1

python ×1

regex ×1