I am stuck in a question. A paragraph which contained some dates in format DD-MM-YYYY, find number of distinct years in the paragraph .Can this be solved using regex?
Asked
Active
Viewed 2,993 times
-1
-
1Pure regex alone can't do this, but regex could be used to isolate and extract the dates. What programming language or tool are you using? – Tim Biegeleisen Apr 01 '18 at 10:55
-
1Also, please post some sample inputs and outputs for the same. – Robo Mop Apr 01 '18 at 11:08
-
I am using JAVA. Some random words with date 12-01-1990 and some more words with date 12-12-2017 and again some random words with same date 12-05-1990. Expected Output: 3 Since it contains 3 dates – Siddharth Poonia Apr 01 '18 at 13:01
-
read this: https://stackoverflow.com/questions/432493/how-do-you-access-the-matched-groups-in-a-javascript-regular-expression – guillaume girod-vitouchkina Apr 01 '18 at 14:44
1 Answers
0
Regex for date var regex = /(?:(?:[0-2][0-9]|[3][01])-(?:[0][13578]|[1][02])|(?:[0-2][0-9]|30)-(?:[0][469]|11)|(?:[0-2][0-9])-02)-[0-9]{4}/g;
.
The above regex cannot match leap years.
To find the count of dates in the pargraph in JS is
function dateCount(input){
const regex = /(?:(?:[0-2][0-9]|[3][01])-(?:[0][13578]|[1][02])|(?:[0-2][0-9]|30)-(?:[0][469]|11)|(?:[0-2][0-9])-02)-[0-9]{4}/g;
let m;
var noDates= 0;
while ((match = regex.exec(input)) !== null) {
dateCounter++;
//This is to prevent from running into infinite loop
if (match.index === regex.lastIndex) {
regex.lastIndex++;
}
}
console.log(dateCounter);
}

AbhishekGowda28
- 994
- 8
- 19