0
我想看看我傳遞的字符串是YYYY-MM-DD格式。Ruby:如何使用正則表達式來查看字符串是否帶有破折號的日期格式?
string = "2013-03-02"
string[/\d{4}-\d{2}-\d{4}/] #why does it return nil?
我要檢查,有4位,其次是一個破折號,隨後2個數字,然後一個破折號,隨後2個數字。
我想看看我傳遞的字符串是YYYY-MM-DD格式。Ruby:如何使用正則表達式來查看字符串是否帶有破折號的日期格式?
string = "2013-03-02"
string[/\d{4}-\d{2}-\d{4}/] #why does it return nil?
我要檢查,有4位,其次是一個破折號,隨後2個數字,然後一個破折號,隨後2個數字。
\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"
你最後\d{4}
需要是\d{2}
。我喜歡http://rubular.com/在Ruby中測試正則表達式。
....我的錯!!!! – Edmund
@埃德蒙發生在每一個..當太多集中發生。 :) –
+1我 - 這太棒了! –