我想检查一个字符串是否是驼峰式大小写(布尔值)。我倾向于使用正则表达式,但任何其他优雅的解决方案都可以。我写了一个简单的正则表达式
(?:[A-Z])(?:[a-z])+(?:[A-Z])(?:[a-z])+
这是正确的吗?还是我错过了什么?
编辑
我想在格式的文本文档集合中捕获名称
McDowell
O'Connor
T.Kasting
编辑2
我已经根据评论中的建议修改了我的正则表达式
(?:[A-Z])(?:\S?)+(?:[A-Z])(?:[a-z])+
我想检查一个字符串是否是驼峰式大小写(布尔值)。我倾向于使用正则表达式,但任何其他优雅的解决方案都可以。我写了一个简单的正则表达式
(?:[A-Z])(?:[a-z])+(?:[A-Z])(?:[a-z])+
这是正确的吗?还是我错过了什么?
编辑
我想在格式的文本文档集合中捕获名称
McDowell
O'Connor
T.Kasting
编辑2
我已经根据评论中的建议修改了我的正则表达式
(?:[A-Z])(?:\S?)+(?:[A-Z])(?:[a-z])+
您可以检查字符串是否同时具有大写和小写字母。
def is_camel_case(s):
return s != s.lower() and s != s.upper() and "_" not in s
tests = [
"camel",
"camelCase",
"CamelCase",
"CAMELCASE",
"camelcase",
"Camelcase",
"Case",
"camel_case",
]
for test in tests:
print(test, is_camel_case(test))
输出:
camel False
camelCase True
CamelCase True
CAMELCASE False
camelcase False
Camelcase True
Case True
camel_case False
您可能想要更多类似的东西:
(?:[A-Z][a-z]*)+
尽管如此,这将允许所有大写字母。您可以通过以下方式避免这种情况:
(?:[A-Z][a-z]+)+
如果需要,使用^
and $
or锚定表达式。\z
使用类似的库将您的字符串转换为驼峰式大小写inflection
。如果它没有改变,它一定已经是骆驼案了。
from inflection import camelize
def is_camel_case(s):
# return True for both 'CamelCase' and 'camelCase'
return camelize(s) == s or camelize(s, False) == s
我认为您可能只需检查字符串前面是否有大写字母和小写字母 if(line =~ m/[az][AZ]/)。在给定的示例中,仅检查 lower 和 upper 失败。〜本
这个正则表达式解决方案适用于我的用例([A-Z][a-z\S]+)([A-Z][a-z]+)
如果您不希望以大写开头的字符串 egCase
和Camelcase
传递True
. 编辑@william 的回答:
def is_camel_case(s):
if s != s.lower() and s != s.upper() and "_" not in s and sum(i.isupper() for i in s[1:-1]) == 1:
return True
return False
tests = [
"camel",
"camelCase",
"CamelCase",
"CAMELCASE",
"camelcase",
"Camelcase",
"Case",
"camel_case",
]
for test in tests:
print(test, is_camel_case(test))
结果:
camel False
camelCase True
CamelCase True
CAMELCASE False
camelcase False
Camelcase False
Case False
camel_case False
sub_string= 'hiSantyWhereAreYou' `Change the string here and try`
index=[x for x,y in enumerate(list(sub_string)) if(y.isupper())] `Finding the index
of caps`
camel_=[]
temp=0
for m in index:
camel_.append(sub_string[temp:m])
temp=m
if(len(index)>0):
camel_.append(sub_string[index[-1]::])
print('The individual camel case words are', camel_) `Output is in list`
else:
camel_.append(sub_string)
print('The given string is not camel Case')
是不带空格或标点符号的短语的做法, 表示用单个大写字母分隔单词
def iscamelcase(string):
non_alpha = [i for i in string if not i.isalpha()]
substrings= string.translate({ord(i): ' ' for i in non_alpha}).split(' ')
for string in substrings:
if not all(char.isupper() for char in string):
for idx,i in enumerate(string):
if i.isupper() and idx > 0:
return True
return False
non_alpha
substrings
输出
camel False
camelCase True
CamelCase True
CAMELCASE False
camelcase False
Camelcase False
Case False
camel_case False