user565
user565

Reputation: 1001

How to check lowerCamelCase string with condition with regex

I am trying to make a regex for the endpoint which can validate a string for lowercase (or concatenated with - )

BUT if there is a curly braces, then a word inside a curly braces should be in lowerCamelCase.

Here is an example string:

/v1/accounts/{accountNumber}/balances
OR /v1/user-account/balances-sheet

I am using a following regex '^[\/a-z\{\}]+$' to validate above examples but not getting the point how I can validate curly braces condition OR if it possible to combine in single Regex?

Upvotes: 1

Views: 91

Answers (3)

Bohemian
Bohemian

Reputation: 424983

Try this:

^(\/([\da-z]+(-[\da-z]+)?|\{[a-z]+([A-Z][a-z]+)*}))+$

See live demo.

Upvotes: 1

huzi8t9
huzi8t9

Reputation: 292

The regex to match both of your examples would be ^([a-z0-9\/\-]+)(\{(?<Token>[\w\/]+)\})?([a-z0-9\/\-]+)?$ -- check it on regex101

Regex 101

Upvotes: 1

anubhava
anubhava

Reputation: 784998

You may use this regex to validate both cases:

^(?:\/\{[a-z]+(?:[A-Z][a-z]*)*\}|\/\w+(?:-\w+)*)+$

RegEx Demo

RegEx Breakup:

  • ^: Start
  • (?:: Start non-capture group
    • \/\{[a-z]+(?:[A-Z][a-z]*)*\}: Match / followed by variable name that would be {<lowerCamelCase>}
    • |: OR
    • \/\w+(?:-\w+)*: Match / followed by valid path component that may have 0 or more hyphen separated words
  • )+: End non-capture group. Repeat this group 1+ times
  • $: End

Upvotes: 1

Related Questions