正则表达式判断字符串是否为中文或英文
可以使用正则表达式来判断一个字符串是否为中文或英文。
判断是否为中文:可以使用正则表达式^[一-龥]+$,其中[一-龥]表示Unicode编码中的中文字符范围。
判断是否为英文:可以使用正则表达式^[a-zA-Z]+$,其中[a-zA-Z]表示英文字母的范围。
示例代码:
import re
def is_chinese_or_english(text):
chinese_pattern = re.compile('^[一-龥]+$')
english_pattern = re.compile('^[a-zA-Z]+$')
if chinese_pattern.match(text):
return '中文'
elif english_pattern.match(text):
return '英文'
else:
return '其他'
text1 = '你好'
text2 = 'hello'
text3 = '你好hello'
text4 = '123'
print(is_chinese_or_english(text1)) # 输出:中文
print(is_chinese_or_english(text2)) # 输出:英文
print(is_chinese_or_english(text3)) # 输出:其他
print(is_chinese_or_english(text4)) # 输出:其他
输出结果:
中文
英文
其他
其他
这段代码中,我们使用re.compile()函数来编译正则表达式,并使用match()函数来进行匹配。如果匹配成功,则返回对应的字符类型。如果不匹配,则返回"其他"。
原文地址: https://www.cveoy.top/t/topic/qqgx 著作权归作者所有。请勿转载和采集!