-2

I have a user input to validate:

String is made up of Part 1 + Part 2. Part 1 can be '$Now' or '$Today' or '$CurrentMonth'. Part 1 is mandatory.

Part 2 can be '+' or '-' Followed by number and a unit. Number can be any number, and Unit should be one of 'm','h','d'. Part 2 is optional

Some valid examples:

'$Now', 
'$Today',
'$CurrentMonth',
'$Now + 2h',
'$Now - 4m',
'$Now + 6d',
'$Today - 7d'

Tried several patterns but wan't able to get through as I have very little knowledge on regex.

red_wolf
  • 77
  • 13

1 Answers1

1

You could use this regex:

^\$(Now|Today|CurrentMonth)\s*(?:([+-])\s*(\d+)([dhm]))?\s*$

It looks for one of $Now, $Today or $CurrentMonth followed by an optional +/-, digits and unit (d, m or h). It captures Part 1 in group 1, then the +/- in group 2, digits in group 3 and unit in group 4 to simplify post processing.

Demo on regex101

Nick
  • 138,499
  • 22
  • 57
  • 95