Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
144
rated 0 times [  151] [ 7]  / answers: 1 / hits: 27537  / 10 Years ago, fri, november 14, 2014, 12:00:00

I have a date in mm/dd/yyyy format. But, depending on what day or month, there is no guarantee that the mm/dd part will necessarily have two digits. So the dates may be:



11/12/2014


or



6/12/2014


or



11/5/2014


In all of the above situations I will need to be able to extract each value for mm, dd, and yyyy so I can do something like this for a calculation:



Month = regex that returns month part.
Day = regex that returns day part
Year = regex that returns 4 digits year part.


This d{2}/d{2}/d{2} matches the whole thing.


More From » regex

 Answers
2

Regexp Solution


The proper regex matching all of your dates is: d{1,2}/d{1,2}/d{4}. Notation
{n,m} is called limiting repetition and in this case d{n,m} means "between n and m digits (inclusive)". You can read more about that here: Limiting Repetition.


If you want to create matching groups, use "(" and ")" (parentheses). Addiitonally, in JavaScript, you have to to escape / with and thus your regexp is: /(d{1,2})/(d{1,2})/(d{4})/


You can use exec function of the regexp to match strings against it. It returns an array containing the matched text as the first element and then one item for each of the matched groups.


You can find out more on MDN RegExp.prototype.exec or see this example below:


const datePattern = /(d{1,2})/(d{1,2})/(d{4})/;
const date = datePattern.exec("11/12/2014"); // ["11/12/2014", "11", "12", "2014"]

Note: If an invalid string is passed (not matching the regular expression) exec function will return null. It's an easy way to do brief validation of users' input or data.


Alternative solution


Alternatively you can simply split the strings:


"11/12/2014".split('/'); // ["11", "12", "2014"]

But this will work regardless of what the string actually contains (it might contain string "ba/tm/an" and split will still return an array with three elements). For this reason, Regexp is probably a better fit if you want to validate the dates.


[#68803] Wednesday, November 12, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
susanajamiep

Total Points: 466
Total Questions: 113
Total Answers: 108

Location: Liberia
Member since Fri, Oct 22, 2021
3 Years ago
susanajamiep questions
Sun, Jun 12, 22, 00:00, 2 Years ago
Mon, Mar 7, 22, 00:00, 2 Years ago
Wed, Jun 10, 20, 00:00, 4 Years ago
Fri, Jan 24, 20, 00:00, 4 Years ago
;