How to match a string not containing a substring using RegEx in Python

1 Answer

0 votes
import re

# ^: Matches the beginning of the string
# (?!notype): asserts that the current position in the string is not followed by the 
#             substring "notype"
# .: Matches any single character (except newline characters)
# *: Matches the preceding group (((?!notype).)) zero or more times
# $: Matches the end of the string

def string_not_containing_substring(pattern, text):
    return bool(re.match(pattern, text, re.IGNORECASE))

pattern = r"^((?!notype).)*$"

print(string_not_containing_substring(pattern, " notype"))
print(string_not_containing_substring(pattern, "notype "))
print(string_not_containing_substring(pattern, "notypevar"))
print(string_not_containing_substring(pattern, "anotypevar"))
print(string_not_containing_substring(pattern, "anotype"))
print(string_not_containing_substring(pattern, "The only approval you need is your own"))
print(string_not_containing_substring(pattern, "Follow your dreams"))
print(string_not_containing_substring(pattern, "Never regret anything that made you smile"))
print(string_not_containing_substring(pattern, "A programming language"))



'''
run:

False
False
False
False
False
True
True
True
True

'''

 



answered Feb 28, 2025 by avibootz

Related questions

1 answer 174 views
1 answer 188 views
1 answer 182 views
1 answer 180 views
1 answer 162 views
1 answer 146 views
...