Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Program to check if String contains only Defined Characters using Regex
When it is required to check if a given string contains only specific characters using regular expression, a regular expression pattern is defined, and the string is subjected to follow this pattern.
Understanding the Regex Pattern
The pattern ^[Python]+$ breaks down as follows:
-
^− Start of string -
[Python]− Character set containing P, y, t, h, o, n -
+− One or more occurrences -
$− End of string
Example
Below is a demonstration of the same −
import re
def check_string(my_string, regex_pattern):
if re.search(regex_pattern, my_string):
print("The string contains the defined characters only")
else:
print("The string does not contain the defined characters only")
# Compile regex pattern - only letters P, y, t, h, o, n allowed
regex_pattern = re.compile('^[Python]+$')
my_string_1 = 'Python'
print("The string is :")
print(my_string_1)
check_string(my_string_1, regex_pattern)
my_string_2 = 'PythonInterpreter'
print("\nThe string is :")
print(my_string_2)
check_string(my_string_2, regex_pattern)
# Additional test cases
my_string_3 = 'Pynot'
print("\nThe string is :")
print(my_string_3)
check_string(my_string_3, regex_pattern)
my_string_4 = 'hello'
print("\nThe string is :")
print(my_string_4)
check_string(my_string_4, regex_pattern)
Output
The string is : Python The string contains the defined characters only The string is : PythonInterpreter The string does not contain the defined characters only The string is : Pynot The string contains the defined characters only The string is : hello The string does not contain the defined characters only
Alternative Approach Using match()
You can also use re.match() which checks if the pattern matches from the beginning of the string −
import re
def validate_string(text, allowed_chars):
pattern = f'^[{allowed_chars}]+$'
return bool(re.match(pattern, text))
# Test with different character sets
test_string = "Python"
allowed_chars = "Python"
result = validate_string(test_string, allowed_chars)
print(f"String '{test_string}' contains only '{allowed_chars}': {result}")
# Test with numbers
test_string2 = "12345"
allowed_chars2 = "12345"
result2 = validate_string(test_string2, allowed_chars2)
print(f"String '{test_string2}' contains only '{allowed_chars2}': {result2}")
String 'Python' contains only 'Python': True String '12345' contains only '12345': True
How It Works
- The
remodule is imported to work with regular expressions - A function
check_stringtakes the string and compiled regex pattern as parameters - The
re.search()method checks if the pattern matches anywhere in the string - The pattern
^[Python]+$ensures the entire string contains only the characters P, y, t, h, o, n - If the pattern matches, the string contains only defined characters; otherwise, it contains other characters
Conclusion
Regular expressions provide a powerful way to validate if strings contain only specific characters. Use ^[characters]+$ pattern to ensure the entire string matches the allowed character set.
Advertisements
