English 中文(简体)
Perl 和regex一样,位于Avre
原标题:Perl like regex in Python

In Perl 我这样做是为了把不同领域划入一个小区,通过()将不同领域分开,并用美元获得。

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

我怎么能做这样的事情呢?

问题回答

“Canonical”-030 translation of You 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.search功能,那么它将汇编你在飞行上的规律),但建议(因此,你不依靠所汇编的可再生能源物体的模块,以达到你的业绩,也为了有抗反射,并使用其方法,而这种方法在沙迦更为常见)。

您可以使用<代码>match方法(从一开始,不论您的格局是否开始采用 ^search方法(在任何地方进行校对);与你的特定模式相当(但我并不相信100%)。

<代码>.groups()方法回收了所有配对群体,以便你能够将其全部分配到一个图纸上(如在Perl使用一个阵列一样,在Perl使用一个阵列,可能更加正常,但由于你选择在Perl中使用ars,你也可以用等同的 Python。

如果任何一行都与RE不相匹配,那一行就会失败,如果你知道,它会受到罚款。 然而,我认为,它会“重新使用”以前的配对线价值,而这种价值是特别的......,除非你再次知道所有线对等。 如果你想要打上非配对线,将最后发言改为:

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

在Perl,你使用阵列比用体积的粗体积充气,要好得多。 E.g.

foreach my $line ( @lines ) { 
    my @matches = ( $line =~ m/(.*?):([^-]*)-(.*)/ );
    ...
}

在Adhury,re模块返回了含有捕获组信息的对应物体。 因此,你可以写:

match = re.search(  (.*?):([^-]*)-(.*) , line )

然后可在<代码>match.group(1)、match.group(2)等上查阅。

编码。 <代码>re.search(> 方法回归MatchObject,其方法有group(), 您可用来检索“捕获组”信息。

例如:

m = re.search(r (.*?):([^-]*)-(.*) , line)
field_1 = m.group(1)
field_2 = m.group(2)
field_3 = m.group(3)

不要忘记,在沙尔,TIMTOWTDI ;

import re
p = re.compile(r (d+).(d+) )
num_parts = p.findall( 11.22   333.444 ) # List of tuples.
print num_parts                          # [( 11 ,  22 ), ( 333 ,  444 )]

举例来说,python为提供了非常微量的支持。 (事实上,金星率先支持被点名的俘虏团体)。

为了使用一个名称的捕获组,你仅添加<代码>? P<the_name_of_group> 在抓获小组的开端括号内。

这使你能够非常容易地从字典上获得你的所有同声:

>>> import re
>>> x = re.search("name: (?P<name>w+) age: (?P<age>d+)", "name: Bob age: 20")
>>> x.groupdict()
{ age :  20 ,  name :  Bob }

The OP s example, amended to use known accreditation groups

import re

find_fields_regex = re.compile(r (?P<field1>.*?):(?P<field2>[^-]*)-(?P<field3>.*) )
for line in lines:
    search_result = find_fields_regex.search(line)
    all_the_fields = search_result.groupdict()

如今,_the_fields is a dictionary with keysponding group name (“field1”、“field2” and “field3”) and the distribution to the content of the respectivetake groups.

www.un.org/Depts/DGACM/index_spanish.htm 为什么你更喜欢点名,

  • With named capture groups, it doesn t matter if you modify the regex pattern to add more capture groups or remove existing capture groups, everything still gets put into the dictionary under the correct keys. But without named capture groups, you have to double check your variable assignments every time the number of groups changes.
  • Named capture groups make your capture groups self-documenting.
  • You can still use numbers to refer to the groups if you want:
>>> import re
>>> x = re.search("name: (?P<name>w+) age: (?P<age>d+)", "name: Bob age: 20")
>>> x.groupdict()
{ age :  20 ,  name :  Bob }
>>> x.group(1)
 Bob 
>>> x.group(2)
 20 

www.un.org/Depts/DGACM/index_spanish.htm 部分优良资源:





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签