Open In App

Python regex to find sequences of one upper case letter followed by lower case letters

Last Updated : 06 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Write a Python Program to find sequences of one upper case letter followed by lower case letters. If found, print 'Yes', otherwise 'No'.

Examples:

Input : Geeks
Output : Yes
Input : geeksforgeeks
Output : No

Python regex to find sequences of one upper case letter followed by lower case letters

Using re.search() To check if the sequence of one upper case letter followed by lower case letters we use regular expression '[A-Z]+[a-z]+$'. 

Python
import re

def findSequence(text):
  	# regex pattern
    pattern = '[A-Z][a-z]+'
    
    # Use re.search to find any match
    if re.search(pattern, text):
        return 'Yes'
    else:
        return 'No'

# Driver program
if __name__ == "__main__":
    word = 'geeAkAA55of55gee4ksabc3Ar2x'
    print(findSequence(word))
    word = 'Geeks'
    print(findSequence(word))
    word = 'geeksforgeeks'
    print(findSequence(word))

Output:

Yes
Yes
No

Time complexity: O(n), where n is length of string.
Auxiliary Space: O(1)



Find those sequences of one upper case letter followed by lower case letters

To find and print all sequences of one uppercase letter followed by lowercase letters in the given text we can use the re.findall() function.

Here's how we can do it:

Python
import re

def findSequences(text):
  	#regex pattern
    pattern = r'[A-Z][a-z]+'
    return re.findall(pattern, text)

# Driver program
if __name__ == "__main__":
    word = 'geeAkAA55of55gee4ksabc3Ar2x'
    print(findSequences(word))
    word = 'Geeks'
    print(findSequences(word))
    word = 'geeksforgeeks'
    print(findSequences(word))


Output:

['Ak', 'Ar']
['Geeks']
[]

Time Complexity: O(n) where n is the length of the input text.

Auxiliary Space Complexity: O(k) where k is the number of matches found.




Next Article

Similar Reads