最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Validating if string contains date - Stack Overflow

programmeradmin0浏览0评论

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 badges
Add a ment  | 

1 Answer 1

Reset to default 6

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){
    //...
}

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.

发布评论

评论列表(0)

  1. 暂无评论