Cod
Cod

Reputation: 309

Camel case pattern matching

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

Answers (2)

The fourth bird
The fourth bird

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 string

Regex demo

If 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_]?$

Regex demo

Upvotes: 1

JvdV
JvdV

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

Related Questions