Huckleberry Carignan
Huckleberry Carignan

Reputation: 2318

Regex for date where month is 1 or 2 digits

I've searched and didn't see this answered so I hope this isn't a repeat / duplicate question.

I'm extracting a date from a string, but moths and days maybe 1 digit or 2 digits. That is, it can be: - "1/1/2018" - "12/1/2018" - "1/12/2018" - "12/12/2018"

I've seen how to Regex where the numbers are constant expected size - or padded with zero

(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.](19|20)\d\d

but how do I make the first digit as optional. And if the first digit is there, how to grab both of them.

Upvotes: 2

Views: 3890

Answers (4)

chaitanya dalvi
chaitanya dalvi

Reputation: 1669

Try this regex.

\d+/\d+/-\d{4}

Upvotes: 0

Vasim Hayat
Vasim Hayat

Reputation: 929

Here is simple way to extract date

function extractDate(dateString){
  var tempArray = dateString.split("/");
  var dateVal = tempArray[0];
  var monthVal = tempArray[1];
  var yearVal = tempArray[2];

  console.log(dateVal);
  console.log(monthVal);
  console.log(yearVal);

}

//Demo 1
extractDate("1/1/2018");

//Demo 2
extractDate("1/12/2018");


//Demo 3
extractDate("12/12/2018");

Plunker Link for testing

Upvotes: -1

justinseibert
justinseibert

Reputation: 176

You can use the + quantifier to match 1 or more of a preceding items. In your case, [0-9]+ (or \d+) would match 1 or 12 or 2018.

Upvotes: 1

leo
leo

Reputation: 3749

To stay with your idea

(0[1-9]|1[012]|[1-9])[- \/.](0[1-9]|[12][0-9]|3[01]|[1-9])[- \/.](19|20)\d\d

Or you could just make the leading zero for days and month optional

(0?[1-9]|1[012])[- \/.](0?[1-9]|[12][0-9]|3[01])[- \/.](19|20)\d\d

Where the question mark is defined as "Matches between zero and one times, as many times as possible, giving back as needed", see https://www.regular-expressions.info/optional.html

Upvotes: 2

Related Questions