Slini Elf Slini Elf - 12 days ago 5
Javascript Question

regex search date in string

I want to search for a date at a string with javascript (e.g. string.search(dateReg);) and show the date when I found it. I found a really nice regex (http://regexr.com/3eoib) but it doesn't work to my string: "27.11." or "27.11.2016" works, but "abcde 27.11.2016 fghi" doesn't work (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 :-).

Answer

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})\b|\b(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])?|(?:(?:16|[2468][048]|[3579][26])00)?)))\b|\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/3