-1

I need to create a regex for a date format in d-mmmm-yyy for an example it will be 7-April-2021

How can i create for the same

I have checked resources

  var dtRegex = new RegExp("^([0]?[1-9]|[1-2]\\d|3[0-1])- (JAN|FEB|MAR|APR|MAY|JUN|JULY|AUG|SEP|OCT|NOV|DEC)-[1-2]\\d{3}$", 'i');

found a similar but, i want to have d not dd how could i achieve this

dev
  • 814
  • 10
  • 27

2 Answers2

0

You have dashes, they had space dash space

https://regex101.com/r/THaJiQ/1

^([0]?[1-9]|[1-2]\d|3[0-1])-(JAN|FEB|MAR|APR|MAY|JUN|JULY|AUG|SEP|OCT|NOV|DEC)-[1-2]\d{3}$
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

You should use a native regular expression, if all you are doing is converting a string with no logic.

Your main issue here is that your month name is full, whereas your valid names are in their three-character representation. Secondly, "JULY" should be "JUL" and you have a space after your first dash in the expression. Lastly, your leading digit expression can be altered to not accept a leading zero.

const ds = '7-Apr-2021';
const expr = /^([1-9]|[12]\d|3[01])-(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)-([1-2]\d{3})$/i;
const [date, month, year] = ds.match(expr).slice(1).map(n => isFinite(n) ? +n : n);

console.log({ year, month, date });
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132