Check if string contains a combination of words excluding certain words with regex

Viewed 180

I am trying to create a regex filter to detect if a string contains a certain substring without certain words.

For example, I want to find all the strings that contain a substring "account manager" and exclude all managers, senior managers and senior account managers

I have tried to use the re.findall(r"account|manager") and then check if the length of the array is 2 and the array doesn't contain words senior or sr.

Instead of this, I would like to create an expression to (exclude words senior and sr) and (include words account and manager) so the condition should return True/False condition values for the following examples:

sr manager - False
senior key account manager - False
sr. key account manager - False
account manager - True
key account manager - True
manager - False
account manager - True

I tried to create something like the following, which is incorrect: (?!senior|sr)(key|account|manager)

Does anyone know what is the right way to check for such condition?

1 Answers

Relying on regex for a simple task is generally a poor idea. Here's a simple, easy-to-read function that passes all your test cases.

from typing import List
def validate_str(s: str, target_substring: str, excluded_strs: List[str]) -> bool:
    if target_substring not in s:
        return False
    if any((i in s for i in excluded_strs)):
        return False
    return True
Related