Reputation: 33
I want to search for a date at a string with javascript. For example:
string.search(dateReg);
Then, show the date when I find it.
I found a really nice regex at (http://regexr.com/3eoib). It works on my string: 27.11.
or 27.11.2016
, but it does not work on abcde 27.11.2016 fghi
(result: -1
).
The regex can't find the date because of these charaters in front and behind the date :/. I googled for 2 hours but didn't found an anwser (how to change the regex the right way?). I also looked at the basis regex-expressions but I coundn't find an answer :/.
Does someone know how to filter the date out of the string?
Thank you :-).
Upvotes: 3
Views: 5810
Reputation: 6088
You could try the same code, but replace $ and ^ with regex word boundry \b
. The code should look like this:
(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})(?=\W)|\b(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])?|(?:(?:16|[2468][048]|[3579][26])00)?)))(?=\W)|\b(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))(\4)?(?:(?:1[6-9]|[2-9]\d)?\d{2})?(?=\b)
The code above will match:
30/04/2016
31/05/2016
But it will not match:
31/04/2016
32/05/2016
and it will match any date that has a string before/after it:
abcde 27.11.2016
Demo: https://regex101.com/r/Hs2sjW/5
Update:
The previous code could have some issues. The best way to do this is to check date pattern first, then check the validity of the date. The first regex that check the date pattern could be something like this:
\d{2}[-.\/]\d{2}(?:[-.\/]\d{2}(\d{2})?)?
Then check the validity of the date with your regex. Here is a working javascript:
var myString = "Test 22/10/20 Test"; //Could be any String
var myRegexp = /\d{2}[-.\/]\d{2}(?:[-.\/]\d{2}(\d{2})?)?/g; //Check pattern only
var validDate = /(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])?|(?:(?:16|[2468][048]|[3579][26])00)?)))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))(\4)?(?:(?:1[6-9]|[2-9]\d)?\d{2})?$/g; //Check the validity of the date
myString = myRegexp.exec(myString)
myString = validDate.exec(myString[0])
console.log(myString[0])
Upvotes: 1