Home > Blockchain >  Python - using Regex to return True if all substrings are contained within string
Python - using Regex to return True if all substrings are contained within string

Time:07-30

str = "chair table planttest"
substr = ["plant", "tab"]
x = func(substr, str)
print(x)

I want code that will return True if str contains all strings in the substr list, regardless of position. If str does not contain all the elements in substr, it should return False.

I have been trying to use re.search or re.findall but am having a very hard time understanding regex operators.

Thanks in advance!

CodePudding user response:

You need to loop through all of the substrings and use the in operator to decide if they are in the string. Like this:

def hasAllSubstrings(partsArr, fullStr):
    allFound = true
    
    for part in partsArr:
        if part not in fullStr:
            allFound = false
    
    return allFound

# Test
full = "chair table planttest"
parts = ["plant", "tab"]
x = hasAllSubstrings(parts, full)
print(x)

Let's see what the hasAllSubstrings function.

  1. It creates a boolean variable that decides if all substrings have been found.

  2. It loops through each part in the partsArr sent in to the function.

  3. If that part is not in the full string fullStr, it sets the boolean to false.

  4. If multiple are not found, it will still be false, and it won't change. If everything is found, it will always be true and not false.

  5. At the end, it returns whether it found everything.

After the function definition, we test the function with your example. There is also one last thing you should take note of: your variables shouldn't collide with built-ins. You used the str variable, and I changed it to full because str is a (commonly used) function in the Python standard library.

By using that name, you effectively just disabled the str function. Make sure to avoid those names as they can easily make your programs harder to debug and more confusing. Oh, and by the way, str is useful when you need to convert a number or some other object into a string.

CodePudding user response:

You can simply use the built-in function all() and the in keyword:

fullstr = "chair table planttest"
substr = ["plant", "tab"]
x = all(s in fullstr for s in substr)

CodePudding user response:

In continuation to the answer of @ Lakshya Raj, you can add break after allFound = false. Because, as soon as the first item of the sub_strung is not found in str, it gives your desired output. No need to loop further.

allFound = false
break
  • Related