使用正则表达式搜索列表中的多个名称?

时间:2013-10-23 16:58:10

标签: python regex python-2.7

我不确定如何完成下面搜索中显示的正则表达式,因为我正在尝试计算项目列表中每个列表中有多少个名称。

Code Snippit

items = ["List: Name-Here", "List: Name-Here, Here, Here'Here, Here-Here'Here, Here Here Here", "List: Here, Here Here, Here Here Here Here"]

for item in items:
    pull1 = re.search(r'(List:)\s+', item)
    pull1 = len(pull1.split(","))
    print pull1,"\n"

预期产出:

1
5
3

任何想法?
- Hyflex

1 个答案:

答案 0 :(得分:4)

这里不需要正则表达式。你的所有名字都以逗号分隔。所以,你可以通过分裂来获得你想要的东西:

>>> items = ["List: Name-Here", "List: Name-Here, Here, Here'Here, Here-Here'Here, Here Here Here", "List: Here, Here Here, Here Here Here Here"]
>>> [len(x.split(",")) for x in items]
[1, 5, 3]
>>>

编辑以回复评论:

我认为这就是你想要的:

from re import findall

mystr = """
List: Name-Here
List: Name-Here, Here, Here'Here, Here-Here'Here, Here Here Here
List: Here, Here Here, Here Here Here Here
"""

items = findall("List:(.+)", mystr)
for item in items:
    print len(item.split(","))

输出:

1
5
3