我是 Python 的新手,想知道将以下 perl 代码写入 python 的最佳方法是什么:
if ($line =~ /(\d)/) {
$a = $1
}
elsif ($line =~ /(\d\d)/) {
$b = $1
}
elsif ($line =~ /(\d\d\d)/) {
$c = $1
}
我想要做的是在一大组行中检索每一行的特定部分。在 python 中,我所能做的就是如下所示,而且非常难看。
res = re.search(r'(\d)', line)
if res:
a = res.group(1)
else:
res = re.search(r'(\d\d)', line)
if res:
b = res.group(1)
else:
res = re.search(r'(\d\d\d)', line)
if res:
c = res.group(1)
有没有人知道在没有非内置模块的情况下编写相同内容的更好方法?
编辑:
如果您需要使用非常不同的 re 来解析行,您该如何编写? 我的意思是它应该很简单,这样任何人都可以理解代码在那里做了什么。 在 perl 中,我们可以这样写:
if ($line =~ /^this is a sample line (.+) and contain single value$/) {
$name = $1
}
elsif ($line =~ /^this is another sample: (.+):(.+) two values here$/) {
($address, $call) = ($1, $2)
}
elsif ($line =~ /^ahhhh thiiiss isiss (\d+) last sample line$/) {
$description = $1
}
在我看来,这种perl代码非常简单易懂。
编辑 2: 我在这里发现了同样的讨论:
http://bytes.com/topic/python/answers/750203-checking-string-against-multiple-patterns
所以没有办法像 perl 一样用 python 写得足够简单..
最佳答案
您可以自己编写一个辅助函数来将匹配结果存储在外部范围内,这样您就不需要在 if 语句中重新匹配正则表达式
def search(patt, str):
search.result = re.search(patt, str)
return search.result
if search(r'(\d)', line):
a = search.result.group(1)
elif search(r'(\d\d)', line):
b = search.result.group(1)
elif search(r'(\d\d\d)', line):
c = search.result.group(1)
在 python 3.8 中,您将能够使用:
if res := re.search(r'(\d)', line):
a = res.group(1)
elif res := re.search(r'(\d\d)', line):
b = res.group(1)
elif res := re.search(r'(\d\d\d)', line):
c = res.group(1)
关于python - 编写类似开关的正则表达式的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29715372/