When it is required to find sequences of an upper case letter followed by lower case using regular expression, a method named ‘match_string’ is defined that uses the ‘search’ method to match a regular expression. Outside the method, the string is defined, and the method is called on it by passing the string.
Example
Below is a demonstration of the same
import re
def match_string(my_string):
pattern = '[A-Z]+[a-z]+$'
if re.search(pattern, my_string):
return('The string meets the required condition \n')
else:
return('The string doesnot meet the required condition \n')
print("The string is :")
string_1 = "Python"
print(string_1)
print(match_string(string_1))
print("The string is :")
string_2 = "python"
print(string_2)
print(match_string(string_2))
print("The string is :")
string_3 = "PythonInterpreter"
print(string_3)
print(match_string(string_3))Output
The string is : Python The string meets the required condition The string is : python The string doesn’t meet the required condition The string is : PythonInterpreter The string meets the required condition
Explanation
The required packages are imported.
A method named ‘match_string’ is defined, that takes a string as a parameter.
It uses the ‘search’ method to check if the specific regular expression was found in the string or not.
Outside the method, a string is defined, and is displayed on the console.
The method is called by passing this string as a parameter.
The output is displayed on the console.