0

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

代码片段

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

有任何想法吗?
- 海福克斯

4

1 回答 1

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
于 2013-10-23T17:00:29.230 回答