正则表达式的Python循环

空白空白空白空白空白空白

suixinyu2009 回答:正则表达式的Python循环

问题

您的测试以查看re.findall是否返回了您想要的值。您的支票:

if test != None:

将始终为真,并且您将始终将word保留的任何值附加到wkar。从re docs(假设python3,但行为没有改变):

  

re.findall(模式,字符串,标志= 0

     

以字符串列表的形式返回字符串中所有不重复的模式匹配项。空匹配项包含在结果中

(重点是我的)

一个空列表不是None,即wkar包含了句子中的所有值。 (有趣的是,这与您在问题开始时提到的行为完全相反。)

解决方案

不要使用正则表达式,这是这项工作的错误工具。这可以使用内置函数来解决。此外,您会因为仅在if语句中可以完成的事情而受到性能的打击

# use the builtin split function to split sentence on spaces
sentence = sentence.split(" ")

wkar = []

# iterate over each word...
for word in sentence:
    #...and see if it matches the test word
    if word == 'text':
    wkar.append(word)
,

re.findall()函数确实会遍历整个句子。您不必自己做那一部分。要获得所需的输出,您要做的就是执行以下操作:

import re

sentence = 'This is some Text,then some more text with some Numbers 1357,and even more text 357,the end.'

wkar = re.findall(r'text',sentence)

这将导致:

['text','text']

,如果您希望re.findall()不区分大小写,请使用:

wkar = re.findall(r'text',sentence,flags=re.IGNORECASE)

将给出:

['Text','text','text']

将来,如果您想测试正则表达式,我建议您使用很棒的https://regex101.com/网站(请确保为python regex字符串格式选择python按钮)。

本文链接:https://www.f2er.com/3150793.html

大家都在问