0

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?

4
  • Why don't you want to use loops? You seem to know the basics of how to approach this, but are stating that it's a constraint that you can't... So.... errr? Would filter suffice? Commented Nov 10, 2013 at 0:40
  • because loops are slow and I have a very big list Commented Nov 10, 2013 at 0:41
  • loops are very slow... really? Premature optimisation and all that... Commented Nov 10, 2013 at 0:42
  • Can you give an example of the code your working on? Commented Nov 10, 2013 at 0:43

1 Answer 1

2

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.