2010-02-06 55 views
2

您好我是Ruby和正則表達式的新手。我試圖用正則表達式除去從一個月或一天任何在零格式,如「1980年2月2日」 =>「1980年2月2日」的日期Ruby正則表達式使用gsub

def m_d_y 
    strftime('%m/%d/%Y').gsub(/0?(\d{1})\/0?(\d{1})\//, $1 + "/" + $2 + "/") 
end 

什麼是錯的這個正則表達式?

謝謝。

回答

2

你可以簡單地刪除0的部分以斜線結束。

對我的作品

require "date" 

class Date 
    def m_d_y 
     strftime('%m/%d/%Y').gsub(/0(\d)\//, "\\1/") 
    end 
end 

puts Date.civil(1980, 1, 1).m_d_y 
puts Date.civil(1980, 10, 1).m_d_y 
puts Date.civil(1980, 1, 10).m_d_y 
puts Date.civil(1908, 1, 1).m_d_y 
puts Date.civil(1908, 10, 1).m_d_y 
puts Date.civil(1908, 1, 10).m_d_y 

輸出

1/1/1980 
10/1/1980 
1/10/1980 
1/1/1908 
10/1/1908 
1/10/1908 
+0

這實際上工作,哈哈,謝謝文森特 – 2010-02-06 08:59:21

+0

一個小的變種也很好地工作: strftime('%m /%d /%Y')。gsub (/ 0(\ d {1})\ //,「\\ 1 /」) – 2010-02-06 09:23:22

+0

是的,Alex。默認的計數器是{1},所以除了清晰之外,沒有必要使用「*」,相當於{0,}和「+」相當於{1,} – 2010-02-06 09:50:42

0

嘗試/(?<!\d)0(\d)/

"02/02/1980".gsub(/(?<!\d)0(\d)/,$1) 
=> "2/2/1980" 
+0

爲什麼這不起作用......它甚至可以解釋正確 – 2010-02-06 08:51:15

+0

咦?你是在做什麼Ruby解釋器? AFAIK(根據http://www.regular-expressions.info/lookaround.html)Ruby不支持look-behind *和* replacement-interpolation是通過''\ 1''(包括引號!)完成的,而不是' $ 1'。 – 2010-02-06 18:55:18

+0

我不確定與其他紅寶石,但紅寶石1.9支持。 – YOU 2010-02-07 03:10:07

0

的問題是,它不會匹配有效日期,以便您的更換將裂傷有效字符串。要解決:

正則表達式:(^|(?<=/))0

更換:''

+0

Ruby爲什麼說這是一個語法錯誤? – 2010-02-06 08:52:11

+0

Ruby不支持look-behind。見:http://www.regular-expressions.info/lookaround.html – 2010-02-06 18:37:56

0

你說的Ruby拋出一個語法錯誤,所以你的問題在於之前,您已經甚至達到了正則表達式。可能因爲你不打電話strftime。嘗試:

def m_d_y 
    t = Time.now 
    t.strftime('%m/%d/%Y').gsub(/0?(\d{1})\/0?(\d{1})\//, $1 + "/" + $2 + "/") 
end 

然後用實時替換Time.now,然後調試您的正則表達式。

+0

我從日期類內調用strftime :) – 2010-02-06 09:22:02

+0

那麼。不知道downvote從哪裏來,但無論如何。 – Ben 2010-02-06 10:07:29

3
"02/02/1980".gsub(/\b0/, '') #=> "2/2/1980" 

\b爲字邊界零寬度的標記,因此\b0不能有零之前一個數字。

2

爲什麼要用正則表達式來處理這個問題?

require "date" 

class Date 
    def m_d_y 
     [mon, mday, year].join("/") 
    end 
end 
+0

不錯,謝謝... – 2010-02-06 19:02:55