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
How to match any one uppercase character in python using Regular Expression?
A regular expression (regex) is a pattern-matching tool that helps find specific characters or patterns in strings. In Python, the re module provides regex functionality. To match uppercase characters, you can use character classes like [A-Z] or specific character sets.
Basic Regex Pattern for Uppercase Characters
The pattern [A-Z] matches any single uppercase letter from A to Z. For specific uppercase characters like vowels, use [AEIOU].
import re
string = 'TutoriAls PoInt Is A Great PlatfOrm to LEarn'
uppercase_vowels = re.findall(r'[AEIOU]', string)
print("Uppercase vowels found:", uppercase_vowels)
Uppercase vowels found: ['A', 'I', 'I', 'A', 'A', 'O', 'E']
Match Any Uppercase Letter
To find all uppercase letters (not just vowels), use the [A-Z] pattern ?
import re
string = 'TutoriAls PoInt Is A Great PlatfOrm to LEarn'
uppercase_letters = re.findall(r'[A-Z]', string)
print("All uppercase letters:", uppercase_letters)
print("Total count:", len(uppercase_letters))
All uppercase letters: ['T', 'A', 'P', 'I', 'I', 'A', 'G', 'P', 'O', 'L', 'E'] Total count: 11
Check Uppercase at Word Start
Use ^[A-Z] to check if a string starts with an uppercase letter ?
import re
strings = ['Python programming', 'javascript language', 'HTML markup']
for text in strings:
if re.match(r'^[A-Z]', text):
print(f"'{text}' starts with uppercase")
else:
print(f"'{text}' does not start with uppercase")
'Python programming' starts with uppercase 'javascript language' does not start with uppercase 'HTML markup' starts with uppercase
Using General Method (Without Regex)
You can also match uppercase characters using string methods and loops ?
string = 'TutoriAls PoInt Is A Great PlatfOrm to LEarn'
uppercase_vowels = []
for char in string:
if char in 'AEIOU':
uppercase_vowels.append(char)
print("Uppercase vowels found:", uppercase_vowels)
Uppercase vowels found: ['A', 'I', 'I', 'A', 'A', 'O', 'E']
Comparison of Methods
| Method | Pattern | Best For |
|---|---|---|
Regex [A-Z]
|
Any uppercase letter | Complex pattern matching |
Regex [AEIOU]
|
Specific uppercase vowels | Targeted character search |
| String methods | char.isupper() |
Simple character checks |
| Manual checking | char in 'AEIOU' |
Basic string operations |
Conclusion
Use regex patterns like [A-Z] for flexible uppercase character matching. For simple cases, string methods or manual checking work well. Regex is more powerful for complex pattern matching scenarios.
