简体   繁体   English

Ruby:如何使用正则表达式查看字符串是否为带破折号的日期格式?

[英]Ruby: How to use regex to see if string is in date format with dashes?

I want to see if the string I passed is in YYYY-MM-DD format. 我想查看我传递的字符串是否为YYYY-MM-DD格式。

string = "2013-03-02"
string[/\d{4}-\d{2}-\d{4}/] #why does it return nil?

I want to check that there are 4 digits, followed by a dash, followed by 2 digits, followed by a dash, followed by 2 digits. 我要检查是否有4位数字,然后是破折号,然后是2位数字,然后是破折号,再是2位数字。

\\d{4}-\\d{2}-\\d{4} should be \\d{4}-\\d{2}-\\d{2} as per your wish. 根据您的意愿, \\d{4}-\\d{2}-\\d{4}应该为\\d{4}-\\d{2}-\\d{2}

(arup~>~)$ pry --simple-prompt
>> string = "2013-03-02"
=> "2013-03-02"
>> string[/\d{4}-\d{2}-\d{2}/]
=> "2013-03-02"
>> string = "2013-03-2"
=> "2013-03-2"
>> string[/\d{4}-\d{2}-\d{2}/]
=> nil
irb(main):001:0> str = "2013-03-02"
=> "2013-03-02"
irb(main):002:0> str[/\d{4}-\d{2}-\d{2}/]
=> "2013-03-02"

Your last \\d{4} needs to be a \\d{2} . 您最后一个\\d{4}必须是\\d{2} I love http://rubular.com/ for testing regex in Ruby. 我喜欢http://rubular.com/,用于在Ruby中测试正则表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM