Search code examples
pythonregexpattern-matchingstring-matching

Return true if all patterns exist in a given string in any order in Python


I want to be able to find out if all of patterns in a given set exist in a string or not. The patterns could be a regex in itself For example, if the input string is:

"Hello World"

Pattern set ("Hel.o Wo*","\*llo","l*d") returns true

Pattern set ("Wor","el.","l*ed") returns false

I know I can iterate through the pattern set and use re.search() but I was looking for one pattern search using re which should do the job. Something like:

re.search("pattern1&pattern2&..","inputString")


Solution

  • You need to use positive lookaheads anchored at the start:

    if re.search(r"^(?=.*pattern1)(?=.*pattern2)(?=.*patternN)", inputString):
        print("yeah!")
    

    The positive lookaheads will actually require the presence of all patterns regardless of their positions in the string.

    The pattern matches:

    • ^ - start of the string
    • (?=.*pattern1) - pattern1 after any 0+ chars other than line break chars *(if re.DOTALL is not used)
    • (?=.*pattern2) - same with pattern2
    • (?=.*patternN) - same with pattern3

    Note the lookahead checks all are executed at the start of the string since lookaheads are zero-width assertions.