gpt4 book ai didi

python - python 中的基本正则表达式问题可帮助我学习它

转载 作者:太空宇宙 更新时间:2023-11-04 10:37:11 25 4
gpt4 key购买 nike

我正在使用本教程来学习 Python 中的正则表达式 - 看起来是一个很棒的教程!

所以教程如下: http://regex101.com/r/vB7mV2

根据教程,我应该使用的代码是:

import re
p = re.compile(r'^(?P<Given>\w+) (?P<Middle>\w\.) (?P<Family>\w+)$', re.MULTILINE)
str = "Jack A. Smith\nMary B. Miller"
m = p.match(str)
print m.group(0)
Jack A. Smith
print m.group(1)
Jack
print m.group(2)
A.
print m.group(3)
Smith
print m.group(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: no such group

令我惊讶的是,我失去了小 Mary B. Miller - 没有 m.group(4)

所以我有几个后续问题:

(1) 我正在使用多行,为什么它只匹配第一个,即示例中的 Jack A. Smith?

(2) 我使用 Given、Middle 和 Family 作为每个匹配项的标签名称,如何使用此类标签访问数据而不仅仅是 m.group(i )

(3) 让我们说我想做匹配和替换?即,我想匹配 Mary B. Miller,并替换为 Jane M. Goldstein,这样被替换的字符串现在将是:str = "Jack A. Smith\nJane M. Goldstein"。我该怎么做? (有点无关,我们称之为奖金 Q)

最佳答案

复制自re.match()

Note that even in MULTILINE mode, re.match() will only match
at the beginning of the string and not at the beginning of each line

这就是为什么您只获得第一场比赛的原因。如果您需要所有匹配项,请使用 re.findall()

将整个正则表达式包装在 () 中是一个示例:

p = re.compile(r'^((?P<Given>\w+) (?P<Middle>\w\.) (?P<Family>\w+))$', re.MULTILINE)
str = "Jack A. Smith\nMary B. Miller"
print re.findall(p, str)

输出:

[('Jack A. Smith', 'Jack', 'A.', 'Smith'), ('Mary B. Miller', 'Mary', 'B.', 'Miller')]

更新::

关于您的问题 2:使用 re.finditer()为了这。一个例子:

p = re.compile(r'^(?P<FullName>(?P<Given>\w+) (?P<Middle>\w\.) (?P<Family>\w+))$', re.MULTILINE)
str = "Jack A. Smith\nMary B. Miller"
matches = re.finditer(p, str)
for match in matches:
info = match.groupdict() ## pulling out the match as dictionary
print info
print info['Family']

问题3:

使用 re.sub()将足以进行此替换。

print re.sub("Mary B\. Miller", "Jane M. Goldstein", str)
## notice I have escaped the . with \.
## in regex . means any non white space characters.

关于python - python 中的基本正则表达式问题可帮助我学习它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22733562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com