Shan
Shan

Reputation: 19293

Searching list of strings using regular expressions in python

I have a list of Strings. I want to select the strings which match a certain pattern using regular expression. Python regular expressions dont take a list and I dont want to use loops.

Any suggestion?

Upvotes: 0

Views: 193

Answers (1)

Tim Peters
Tim Peters

Reputation: 70735

Try:

def searcher(s):
    if COMPILED_REGEXP_OBJECT.search(s):
        return s

matching_strings = filter(searcher, YOUR_LIST_OF_STRING)

searcher() returns the string if it matches, else returns None. filter() only returns "true" objects, so will skip the Nones. It will also skip empty strings, but doubt that's a problem.

Or, better, as @JonClements pointed out:

matching_strings = filter(COMPILED_REGEXP_OBJECT.search, YOUR_LIST_OF_STRING)

Not only shorter, it only looks up the .search method once (instead of once per string).

Upvotes: 2

Related Questions