admin管理员组文章数量:1417555
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!
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!
Share Improve this question asked Sep 16, 2015 at 12:37 Roland RuulRoland Ruul 1,2529 silver badges15 bronze badges1 Answer
Reset to default 6Well 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){
//...
}
Here is a working example
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.
本文标签: javascriptValidating if string contains dateStack Overflow
版权声明:本文标题:javascript - Validating if string contains date - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745263060a2650443.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论