Python Program to check if String contains only Defined Characters using Regex


When it is required to check if a given string contains specific characters using regular expression, a regular expression pattern is defined, and the string is subjected to follow this pattern.

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 doesnot string contain the defined characters")

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)

Output

The string is :
Python
The string contains the defined characters
The string is :
PythonInterpreter
The doesn’t string contain the defined characters

Explanation

  • The required packages are imported.

  • A method named ‘check_string’ is defined, and it takes the string and a regular expression as parameters.

  • The ‘search’ method is called and checked to see if a specific set of characters is present in the string.

  • Outside the method, the ‘compile’ method is called on the regular expression.

  • The string is defined and is displayed on the console.

  • The method is called by passing this string.

  • The output is displayed on the console.

Updated on: 20-Sep-2021

318 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements