Last Updated : 15 Jul, 2025
In this article, we are going to see how to check whether the given string contains only a certain set of characters in Python. These defined characters will be represented using sets.
Examples:
AlgorithmInput: ‘657’ let us say regular expression contains the following characters- (‘78653’)
Output: Valid
Explanation: The Input string only consists of characters present in the given string.
Input: ‘7606’ let us say regular expression contains the following characters-
(‘102’)Output: Invalid
Explanation: The input string consists of characters not present in given string.
Step 1: Define the pattern of the string using RegEx.
Step 2: Match the string with the specified pattern
Step 3: Print the Output
Check if String Contains Only Defined Characters using RegexThe method or approach is simple we will define the character set using a regular expression. The regular expression is a special pattern or sequence of characters that will allow us to match and find other sets of characters or strings.
Functions Used:
Below is the implementation.
Python3
# _importing module
import re
def check(str, pattern):
# _matching the strings
if re.search(pattern, str):
print("Valid String")
else:
print("Invalid String")
# _driver code
pattern = re.compile('^[1234]+$')
check('2134', pattern)
check('349', pattern)
Output:
Valid String Invalid String
Note: You can also use re.match() in place of re.search()
Time complexity : O(n)
Space Complexity : O(1)
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4