Reputation: 309
I want to make sure key Name which I had extracted from api is in valid camel case format only , I used following regex ^[a-z]+([A-Z][a-z0-9]+)*$ which do make sure that string start with lowerCase only , how can make sure following condition
first and last character can only be in lowercase or underscore. No special special character including underscore is there in between first and last string index.'
Upvotes: 0
Views: 1261
Reputation: 163577
You might use
^[a-z_][a-z]*(?:[A-Z][a-z0-9]+)*[a-z0-9_]?$
^
Start of string[a-z_][a-z]*
Match one of the listed including the _
(?:[A-Z][a-z0-9]+)*
Optionally repeat an uppercase char and 1+ lowercase chars[a-z0-9_]?
Optionally match one of the listed including the _
$
End of stringIf there should be only lowercase chars or an underscore at the end, the uppercase char should be followed by a lowercase char and you don't want to match only underscores:
^(?!_+$)[a-z_][a-z]*(?:[A-Z][a-z0-9]+)*[a-z_]?$
Upvotes: 1
Reputation: 75960
Looks like the following could work:
^(?!.+_.)[a-z_]\w*[a-z_]$
See the online demo
^
- Start line anchor.(?!.+_.)
- Negative lookahead to prevent an underscore other than at the start/end index.[a-z_]\w*[a-z_]
- A single lowercase alpha or underscore followed by 0+ word-characters and again a single lowercase alpha or underscore.$
- End line anchor.Upvotes: 1