Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7952619
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T02:54:54+00:00 2026-06-04T02:54:54+00:00

I have a function that returns True if a string matches at least one

  • 0

I have a function that returns True if a string matches at least one
regular expression in a list and False otherwise. The function is called
often enough that performance is an issue.

When running it through cProfile, the function is spending about 65% of
its time doing matches and 35% of its time iterating over the list.

I would think there would be a way to use map() or something but I can’t
think of a way to have it stop iterating after it finds a match.

Is there a way to make the function faster while still having it return
upon finding the first match?

def matches_pattern(str, patterns):
    for pattern in patterns:
        if pattern.match(str):
            return True
    return False
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T02:54:55+00:00Added an answer on June 4, 2026 at 2:54 am

    The first thing that comes to mind is pushing the loop to the C side by using a generator expression:

    def matches_pattern(s, patterns):
        return any(p.match(s) for p in patterns)
    

    Probably you don’t even need a separate function for that.

    Another thing you should try out is to build a single, composite regex using the | alternation operator, so that the engine has a chance to optimize it for you. You can also create the regex dynamically from a list of string patterns, if this is necessary:

    def matches_pattern(s, patterns):
        return re.match('|'.join('(?:%s)' % p for p in patterns), s)
    

    Of course you need to have your regexes in string form for that to work. Just profile both of these and check which one is faster 🙂

    You might also want to have a look at a general tip for debugging regular expressions in Python. This can also help to find opportunities to optimize.

    UPDATE: I was curious and wrote a little benchmark:

    import timeit
    
    setup = """
    import re
    patterns = [".*abc", "123.*", "ab.*", "foo.*bar", "11010.*", "1[^o]*"]*10
    strings = ["asdabc", "123awd2", "abasdae23", "fooasdabar", "111", "11010100101", "xxxx", "eeeeee", "dddddddddddddd", "ffffff"]*10
    compiled_patterns = list(map(re.compile, patterns))
    
    def matches_pattern(str, patterns):
        for pattern in patterns:
            if pattern.match(str):
                return True
        return False
    
    def test0():
        for s in strings:
            matches_pattern(s, compiled_patterns)
    
    def test1():
        for s in strings:
            any(p.match(s) for p in compiled_patterns)
    
    def test2():
        for s in strings:
            re.match('|'.join('(?:%s)' % p for p in patterns), s)
    
    def test3():
        r = re.compile('|'.join('(?:%s)' % p for p in patterns))
        for s in strings:
            r.match(s)
    """
    
    import sys
    print(timeit.timeit("test0()", setup=setup, number=1000))
    print(timeit.timeit("test1()", setup=setup, number=1000))
    print(timeit.timeit("test2()", setup=setup, number=1000))
    print(timeit.timeit("test3()", setup=setup, number=1000))
    

    The output on my machine:

    1.4120500087738037
    1.662621021270752
    4.729579925537109
    0.1489570140838623
    

    So any doesn’t seem to be faster than your original approach. Building up a regex dynamically also isn’t really fast. But if you can manage to build up a regex upfront and use it several times, this might result in better performance. You can also adapt this benchmark to test some other options 🙂

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a custom type MyType with a function MyBoolFunction(string) that returns true or
I have a function that returns TRUE or FALSE or Test_operation , and I
We have a table value function that returns a list of people you may
Here is a typical function that returns either true/false; private static bool hasValue() {
I have a function isNotEmpty which returns true if the string is not empty
I have a function on my server code that returns a list of ElementRow
I have the following function that executes an query and returns true on success
I have a view. the view has a function that returns a text string
I have a function findLocalEvents() that returns a list of items I want to
I have a function that returns an entry on a dictionary, based on the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.