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.


Below is a demonstration of the same

import re
def check_string(my_string, regex_pattern):

   if, my_string):
      print("The string contains the defined characters only")
      print("The doesnot string contain the defined characters")

regex_pattern = re.compile('^[Python]+$')

my_string_1 = 'Python'
print("The string is :")
check_string(my_string_1 , regex_pattern)

my_string_2 = 'PythonInterpreter'
print("\nThe string is :")
check_string(my_string_2, regex_pattern)


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


  • 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.