Reputation: 1242
Im currently facing a problem:
I have .txt file which im going through.. I want to validate if a line of text contains date (format: yyyy/mm/dd).
Line example: 2015/01/05 12 John's mother.
Regex im using: var dateType = /^(\d{4})([\/-])(\d{1,2})\2(\d{1,2})$/;
What would be the best way to reach this?
Thank you in advance!
Upvotes: 1
Views: 4336
Reputation: 48435
Well the only real problem with your regex not working is that you are trying to match start ^
and end $
. So remove those for a 'contains' logic:
/(\d{4})([\/-])(\d{1,2})\2(\d{1,2})/
You can then use this regex in your javascript with the test()
function as follows:
var dateType = /(\d{4})([\/-])(\d{1,2})\2(\d{1,2})/;
var isMatch = dateType.test(myLine[i]);
if(isMatch){
//...
}
However, if you know it will always start with a date, then keep the ^
. That way you are less likely to get unexpected matches if for example you don't want lines that end with a date.
Upvotes: 6