Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
缩短Python中正则表达式的使用语法_Python_Regex - Fatal编程技术网

缩短Python中正则表达式的使用语法

缩短Python中正则表达式的使用语法,python,regex,Python,Regex,我很抱歉,因为我来自Perl,而且我是Python新手 以下示例在我看来很长: #!/usr/bin/python import re r = re.compile('(?i)m(|[ldf])(\d+)') m = r.match(text) if m: print m.group(2) 例如,在Perl中,它只有一行,可读性很强 #!/usr/bin/perl print $2 if /m(|[ldf])(\d+)/i 如何将Python示例重写得更简单。如果可能的话,可以像Pe

我很抱歉,因为我来自Perl,而且我是Python新手

以下示例在我看来很长:

#!/usr/bin/python
import re
r = re.compile('(?i)m(|[ldf])(\d+)')
m = r.match(text)
if m:
    print m.group(2)
例如,在Perl中,它只有一行,可读性很强

#!/usr/bin/perl
print $2 if /m(|[ldf])(\d+)/i
如何将Python示例重写得更简单。如果可能的话,可以像Perl一样轻松

我计划编写大量的测试,如果我想保持代码的可读性,我希望避免使用那些不会帮助人们理解我的程序的行。我想下面这样的内容比我的第一个解决方案更具可读性:

r = R()
if r.exec('(?i)m(|[ldf])(\d+)', text):    print r.group(2)
if r.exec('(?i)k(|[rhe])(\d{2})', text):  print r.group(2)

不幸的是,在这种情况下,我必须为此编写一个类

Python的方式重视清晰而不是简洁,因此事情通常会比Perl中的更详细。也就是说,
re.compile
步骤是可选的

m = re.match('(?i)m(|[ldf])(\d+)', text)
if m:
  print m.group(2)

在Python中,赋值不是表达式;它们不能用作值。因此,无法跳过单独的赋值语句(
m=…
)或将其与
if
组合。如果以后要引用匹配对象,您确实需要一个显式赋值-没有类似于自动存储捕获组的Perl
$n
变量的全局隐式状态。

编译模式不是强制性的。Perl中一行中的某些内容可以/不一定是python中的一行。可读性取决于旁观者。添加到khelwood的注释:Python不是Perl。不要试图将Perl语法塞进Python(比如正则表达式或其他东西)。
os.system('Perl-your_-Perl\u-script.pl')
以获得与Perl语法的完全兼容性。@noox在这种上下文中“矫揉造作”的定义是什么?字典里没有这个词,所以我不知道你的意思;我想nowox的意思是“任务”@NewWorld。