使用regexp,如何查找仅包含大写或小写的字符串

时间:2013-08-11 20:09:51

标签: python regex python-3.x

我需要检查整个字符串的大小写。并且只打印全部大写或小写的那些。

这是我写的代码。

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)

3 个答案:

答案 0 :(得分:4)

使用upper()lower()字符串方法,而不是正则表达式。

if string.lower() == string or string.upper() == string:
    print string

如果只允许使用字母,请检查string.isalpha()

如果需要正则表达式,那么您的问题就是不检查整个字符串。

exp = re.compile("^([a-z]{2,}|[A-Z]{2,})$")

这将确保整个字符串需要适合模式,而不仅仅是它的一部分。

答案 1 :(得分:1)

我不明白为什么你需要使用正则表达式,但无论如何:

if re.match('[a-z]+$', text) or re.match('[A-Z]+$', text):
    # is all lower or all upper

简化为:

if re.match('([a-z]+|[A-Z]+)$', text):
    # is all lower or all upper

答案 2 :(得分:0)

这有效:

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')   
相关问题