Reputation: 424
I need to check the entire string for case. and only print those with all uppercase OR lowercase.
Here's the code I've written.
import re
lower = 'abcd'
upper = 'ABCD'
mix = 'aB'
mix2 = 'abcD'
exp = re.compile("[a-z]{2,}|[A-Z]{2,}")
lower_m = re.findall(exp,lower)
upper_m = re.findall(exp,upper)
mix_m = re.findall(exp,mix)
mix2_m = re.findall(exp,mix2)
print(lower_m)
print(upper_m)
print(mix_m)
print(mix2_m)
Upvotes: 1
Views: 6593
Reputation: 103754
This works:
import re
st='''abcd
ABCD
aB
abcD'''
for line in st.splitlines():
line=line.strip()
if re.search(r'^[a-z]+$',line):
print(line,'only lower')
continue
if re.search(r'^[A-Z]+$',line):
print(line,'only upper')
continue
if re.search(r'^[a-zA-Z]+$',line):
print(line,'mixed case')
Upvotes: 0
Reputation: 4961
Use the upper()
and lower()
string methods, rather than a regex.
if string.lower() == string or string.upper() == string:
print string
If only letters are allowed, also check that string.isalpha()
.
If a regex is necessary, the problem with yours is that you don't check the entire string.
exp = re.compile("^([a-z]{2,}|[A-Z]{2,})$")
This will ensure that the entire string needs to fit the pattern, rather than just part of it.
Upvotes: 6
Reputation: 142136
I don't see why you need to use a regex, but anyway:
if re.match('[a-z]+$', text) or re.match('[A-Z]+$', text):
# is all lower or all upper
Which simplifies to:
if re.match('([a-z]+|[A-Z]+)$', text):
# is all lower or all upper
Upvotes: 1