![]() |
VOOZH | about |
Given a string, the task is to check whether it contains only a specific set of allowed characters. For example:
Allowed characters: a-z
Input: "hello" -> Valid
Input: "hi!" -> InvalidAllowed characters: 0-9
Input: "657" -> Valid
Input: "72A" -> Invalid
Let’s explore different regex-based methods to perform this check in Python.
fullmatch() checks if the entire string is made up of only the allowed characters. If even one invalid character appears, the match fails.
Valid string
Explanation:
match() begins checking from the start, so we add ^ and $ to ensure the entire string must match the allowed characters.
Valid string
Explanation:
Instead of matching allowed characters, we search for characters not allowed using re.search(). If we find any such character then, invalid.
Invalid string
Explanation:
findall() collects all invalid characters. If the result list is empty string contains only allowed characters.
Invalid string: ['!', '@', '#']
Explanation: