Perl 喜欢 Python 中的正则表达式 [英] Perl like regex in Python

查看:39
本文介绍了Perl 喜欢 Python 中的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Perl 中,我会做这样的事情来获取正则表达式中的不同字段,用 () 分隔不同的字段并使用 $

In Perl I would do something like this for taking different fields in a regexp, separating different fields by () and getting them using $

foreach $line (@lines)
{
 $line =~ m/(.*?):([^-]*)-(.*)/;
  $field_1 = $1
  $field_2 = $2
  $field_3 = $3
}

我怎么能用 Python 做这样的事情?

How could I do something like this in Python?

推荐答案

"Canonical" Python 翻译您的代码片段...:

"Canonical" Python translation of your snippet...:

import re

myre = re.compile(r'(.*?):([^-]*)-(.*)')
for line in lines:
    mo = myre.search(line)
    field_1, field_2, field_3 = mo.groups()

导入 re 是必须的(导入通常在模块的顶部完成,但这不是强制性的).预编译 RE 是可选的(如果您改用 re.search 函数,它将即时编译您的模式)但推荐(因此您不要依赖已编译的 RE 对象的模块缓存来你的表现,也是为了拥有一个 RE 对象并调用它的方法,这在 Python 中比较常见).

Importing re is a must (imports are normally done at the top of a module, but that's not mandatory). Precompiling the RE is optional (if you use the re.search function instead, it will compile your pattern on the fly) but recommended (so you don't rely on the module cache of compiled RE objects for your performance, and also in order to have a RE object and call its methods, which is more common in Python).

您可以使用 match 方法(它总是从头开始尝试匹配,无论您的模式是否以 '^' 开头)或 search 方法(尝试在任何地方匹配);使用您给定的模式,它们应该是等效的(但我不是 100% 确定).

You can use either the match method (which always tries matching from the start, whether or not your pattern starts with '^') or the search method (which tries matching anywhere); with your given pattern they should be equivalent (but I'm not 100% sure).

.groups() 方法返回所有匹配的组,因此您可以一次性将它们全部分配(在 Python 中使用列表,就像在 Perl 中使用数组一样,可能更正常,但是由于您选择在 Perl 中使用标量,因此您也可以在 Python 中执行相同的操作).

The .groups() method returns all matching groups so you can assign them all in one gulp (using a list in Python, just like using an array in Perl, would probably be more normal, but since you chose to use scalars in Perl you can do the equivalent in Python too).

如果任何行与 RE 不匹配,这将失败并出现异常,如果您知道它们都匹配,这很好(我不确定您的 Perl 的行为是什么,但我认为它会重用"以前的而是匹配行的值,这很奇怪……除非,您再次知道所有行都匹配;-).如果只想跳过不匹配的行,请将最后一条语句更改为以下两条:

This will fail with an exception if any line does not match the RE, which is fine if you know they all do match (I'm not sure what's the behavior of your Perl but I think it would "reuse" the previous matching line's values instead, which is peculiar... unless, again you know all lines match;-). If you want to just skip non-matching lines, change the last statement to the following two:

    if mo:
        field_1, field_2, field_3 = mo.groups()

这篇关于Perl 喜欢 Python 中的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆