Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for camel case in Python

I would like to check if a string is a camel case or not (boolean). I am inclined to use a regex but any other elegant solution would work. I wrote a simple regex

(?:[A-Z])(?:[a-z])+(?:[A-Z])(?:[a-z])+

Would this be correct? Or am I missing something?

Edit

I would like to capture names in a collection of text documents of the format

McDowell
O'Connor
T.Kasting

Edit2

I have modified my regex based on the suggestion in the comments

(?:[A-Z])(?:\S?)+(?:[A-Z])(?:[a-z])+
like image 665
Dexter Avatar asked Apr 16 '12 22:04

Dexter


2 Answers

You could check if a string has both upper and lowercase.

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))

Output:

camel False
camelCase True
CamelCase True
CAMELCASE False
camelcase False
Camelcase True
Case True
camel_case False
like image 105
William Bettridge-Radford Avatar answered Oct 27 '22 02:10

William Bettridge-Radford


You probably want something more like:

(?:[A-Z][a-z]*)+

Altho that would allow all caps. You could avoid that with:

(?:[A-Z][a-z]+)+

Anchor the expression with ^ and $ or \z if required.

like image 22
Qtax Avatar answered Oct 27 '22 03:10

Qtax