简体   繁体   中英

Upper and Lower camel case

I am trying to come up with a regex for both Upper and lower Camel case.

Here is what I tried

(([A-Z][a-z0-9]*){2,}|([a-z][A-Z0-9]*){2,})

Trying to match Upper camel case with this - ([AZ][a-z0-9] ){2,} but it is matching other combinations as well. Similar is the case with the second part - ([az][A-Z0-9] ){2,})

This would match upper and lower camel case phrases containing at least one upper case in the word.

Upper Camel Case

[A-Z][a-z0-9]*[A-Z0-9][a-z0-9]+[A-Za-z0-9]*

example:HelloWorld, AQuickBrownFox

Lower Camel Case

[a-z]+[A-Z0-9][a-z0-9]+[A-Za-z0-9]*

example: helloWorld, aQuickBrownFox

For lowerCamelCase you need:

  1. A lowerCaseLetter
  2. at least one (lowerCaseLetter or UpperCaseLetter or numb3r)

So an approriate regex would be

[a-z][a-zA-Z0-9]+

Similarly for UpperCamelCase, you'll have [AZ][a-zA-Z0-9]+ , and if you group those, you get

[a-zA-Z][a-zA-Z0-9]+

Edit: If you strictly require that for a word to be a camel case word, it heeds to have a "hump", where a hump is an uppercase letter or a number, you need:

  1. An upper or a lower case letter, followed by
  2. Other lower case letters (maybe none), followed by
  3. A hump, followed by
  4. Other lower case letters (maybe none),
  5. Maybe followed by another hump(s)

Then your regex is:

[a-zA-Z][a-z]*([A-Z0-9]+[a-z]*)+

Regex fiddle

Lower Camel Case - no digits allowed


    ^[a-z][a-z]*(([A-Z][a-z]+)*[A-Z]{0,1}|([a-z]+[A-Z])*|[A-Z])$
    

Test Cases: https://regex101.com/library/4h7A1I

Lower Camel Case - digits allowed


    ^[a-z][a-z0-9]*(([A-Z][a-z0-9]+)*[A-Z]{0,1}|([a-z0-9]+[A-Z])*|[A-Z])$

Test Cases: https://regex101.com/library/8nQras

Lower Camel Case - digits allowed - Upto 3 upper case letters

To match more than one upper case letter (eg. deviceID , serialNo , awsVPC ) it gets slightly more involved:

 
    ^[a-z][a-z0-9]*(([A-Z]{1,3}[a-z0-9]+)*[A-Z]{0,3}|([a-z0-9]+[A-Z]{1,3})*|[A-Z]{1,3})$

Test Cases: https://regex101.com/library/C2eHyc

Pascal Case - no digits allowed


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

Test Cases: https://regex101.com/library/sF2jRZ

Pascal Case - digits allowed


    ^[A-Z](([a-z0-9]+[A-Z]?)*)$

Test Cases: https://regex101.com/library/csrkQw

Pascal Case - digits allowed - Upto 3 upper case letters

To match more than one upper case letter (eg. DeviceID , SerialNo , AwsVPC , IOStream , StreamIO ) it gets slightly more involved:


    ^[A-Z](([A-Z]{1,2}[a-z0-9]+)+([A-Z]{1,3}[a-z0-9]+)*[A-Z]{0,3}|([a-z0-9]+[A-Z]{0,3})*|[A-Z]{1,2})$

Test Cases: https://regex101.com/library/TLTXbK

For more details on camel case and pascal case check out this repo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM