简体   繁体   中英

Searching with regex for a number of names in a list?

I'm unsure how to complete the regex shown in the search below, as I'm trying to count how many names there are in each list within my items list.

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"

Expected Output:

1
5
3

Any ideas?
- Hyflex

Regex isn't needed here. All of your names are comma-separated. So, you can get what you want by just splitting on that:

>>> 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]
>>>

Edit in response to comment:

I think this is what you want:

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(","))

output:

1
5
3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM