javascript - Validating if string contains date - Stack Overflow

Im currently facing a problem:I have .txt file which im going through.. I want to validate if a line of

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745263061a4619298.html

相关推荐

  • javascript - Validating if string contains date - Stack Overflow

    Im currently facing a problem:I have .txt file which im going through.. I want to validate if a line of

    4小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信