Home > OS >  how to check lowerCamelCase string with condition with Regix
how to check lowerCamelCase string with condition with Regix

Time:09-14

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?

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

Try this:

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

See live demo.

  • Related