Prerequisites: Regular Expression in Python
Given a string. The task is to count the number of Uppercase, Lowercase, special character and numeric values present in the string using Regular expression in Python.
Examples:
Input :
"ThisIsLazyroar!, 123"
Output :
No. of uppercase characters = 4
No. of lowercase characters = 15
No. of numerical characters = 3
No. of special characters = 2
Python program to Count Uppercase, Lowercase, special character and numeric values using Regex
Example 1:
The re.findall(pattern, string, flags=0) method can be used to find all non-overlapping matches of a pattern in the string. The return value is a list of strings.
Below is the implementation.
Python3
import restring = "ThisIsLazyroar !, 123"# Creating separate lists using# the re.findall() method.uppercase_characters = re.findall(r"[A-Z]", string)lowercase_characters = re.findall(r"[a-z]", string)numerical_characters = re.findall(r"[0-9]", string)special_characters = re.findall(r"[, .!?]", string)print("The no. of uppercase characters is", len(uppercase_characters))print("The no. of lowercase characters is", len(lowercase_characters))print("The no. of numerical characters is", len(numerical_characters))print("The no. of special characters is", len(special_characters)) |
Output:
The no. of uppercase characters is 4
The no. of lowercase characters is 15
The no. of numerical characters is 3
The no. of special characters is 4
Time complexity : O(n)
Space Complexity : O(n)
Example 2:
Python3
import redef count_characters(input_string): uppercase_count = len(re.findall(r'[A-Z]', input_string)) lowercase_count = len(re.findall(r'[a-z]', input_string)) special_char_count = len(re.findall(r'[!@#$%^&*()_+{}\[\]:;<>,.?\\/-]', input_string)) numeric_count = len(re.findall(r'[0-9]', input_string)) return uppercase_count, lowercase_count, special_char_count, numeric_counttest_string = "Hello World! 123"uppercase, lowercase, special_chars, numeric = count_characters(test_string)print("Uppercase count:", uppercase)print("Lowercase count:", lowercase)print("Special character count:", special_chars)print("Numeric count:", numeric) |
Output:
Uppercase count: 2
Lowercase count: 8
Special character count: 1
Numeric count: 3
