Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

checking if string contains substring with variations

i want to recognize if a user says somthing like "Hey David" oder "Hi Max" and then do something. i got the voice recognition and convertion but i dont know how to check for the variations like hey, hi plus the names like david or amy or whatever.

i tried to check the string with a reg ex but it only checks for the first variations.

if any(re.findall(r'hi|Hey' + r'Amy|David', string, re.IGNORECASE)):
    print("test")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use regular expressions, but you’ll need to structure your regex pattern correctly. Your current approach only checks for the presence of either "Hi" or "Hey" and then one of the names "Amy" or "David" in sequence.

import re

# Example list of greetings and names to check for
greetings = ["Hi", "Hey", "Hello"]
names = ["Amy", "David", "Max"]

# Sample input text
text = "Hey David, how are you?"

# Construct a regex pattern to match variations
pattern = rf'({"|".join(greetings)})\s+({"|".join(names)})'
# The pattern will look like: (Hi|Hey|Hello)\s+(Amy|David|Max)

if re.search(pattern, text, re.IGNORECASE):
    print("Recognized a greeting and name in the text.")
    # Perform your action here
else:
    print("No match found.")

In this code, we create lists of greetings and names you want to recognize.
The "|" character is used to create an OR condition within the pattern. We use "\s+" to match one or more spaces between the greeting and the name. The "re.IGNORECASE" flag ensures that the pattern matching is case-insensitive.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading