Python re.findall()在此代码中的用途

时间:2016-12-22 14:42:37

标签: python regex python-2.7

我目前正在学习Python,我正在尝试破译我在网上找到的代码。代码的要点是将原始字符串与用户输入键进行比较,如果匹配,则返回原始字符串。

我在尝试理解re.findall()在此代码中做了什么时遇到了问题

因此head [0]包含数据字符串

  

('2016-12-22 06:28:36',u'Kith x New Era K 59FIFTY Cap - Pink',   的u 'http://kithnyc.com/products/kith-x-new-era-59fifty-cap-pink')

键包含原始字符串

  

键= r'Nike |超'

head = self.data
for k in key:
    print k
    flag=re.findall(k,str(head[0]),flags=re.I)
    print len(flag)
    if len(flag)>4:
        print head[0]

根据我的理解,代码的目的是循环键并查看它是否与head [0]匹配。如果匹配,则返回head [0]。然而,它仍在返回,头[0]

  

('2016-12-22 06:28:36',u'Kith x New Era K 59FIFTY Cap - Pink',   的u 'http://kithnyc.com/products/kith-x-new-era-59fifty-cap-pink')

即使它不匹配。

1 个答案:

答案 0 :(得分:1)

  

如果项目与关键字正则表达式匹配,则假设打印在头部。

然后使用following code

import re
head = ('2016-12-22 06:28:36', 'nike item', 'ultra item', 'Kith x New Era K 59FIFTY Cap - Pink', 'http://kithnyc.com/products/kith-x-new-era-59fifty-cap-pink')
key=r'Nike|Ultra'  # This is a regex pattern, matches `Nike` or `Ultra` 
for s in head:     # Iterate the items in head
    if re.search(key, s, flags=re.I): # Search for a match in each item, case insensitively
        print(s)  # Print if found

输出:nike itemultra item

在代码中,使用for k in key:循环遍历模式的字符。使用re.findall,搜索了所有非重叠匹配项,以匹配k中的单个字符,仅检查head[0],不考虑所有其他项目。

相关问题