mdaniels
mdaniels

Reputation: 109

Counting occurances in a list using regular expressions

I currently have a list that looks like the following:

list = [me foo, i foobar, the barfoo, foo tool, the too]

I want to count the number of exact instances of "foo" OR "too", but it would exclude "barfoo" and "tool".

I can do a simple search using the following code (which returns the right results), but I'd like to use regular expressions on "foo" and "too". Any help?

sum(('foo' in i or 'too' in i) for i in list)

I'm familiar with the following code, though I can't get it to work with a list.

import re
re.search(r'\bfoo\b', list)

Upvotes: 0

Views: 64

Answers (1)

roippi
roippi

Reputation: 25954

It's similar - you just need to convert the result of the re.search into a bool. re.search will be None if no match is found - ie False - otherwise True.

li = ['me foo', 'i foobar', 'the barfoo', 'foo tool', 'the too']

sum(bool(re.search(r'\b(f|t)oo\b',x)) for x in li)
Out[80]: 3

(standard reminder not to name your lists list goes here)

Upvotes: 1

Related Questions