2014-03-25 167 views
0

我從文件中的字符串,看起來像這樣: 紅寶石包裝日期

"[[5473, 992, 'smth', Tue, 25 Mar 2014 05:08:12 UTC +00:00, Fri, 07 Mar 2014 22:55:42 UTC +00:00], [5473, 993, 'smth', Tue, 25 Mar 2014 14:38:05 UTC +00:00, Fri, 07 Mar 2014 22:57:33 UTC +00:00], [6084, 994, 'smth', Mon, 24 Mar 2014 23:37:37 UTC +00:00, Mon, 24 Mar 2014 23:37:37 UTC +00:00], [6084, 995, 'smth', nil, nil], [6084, 996, 'smth', nil, nil], [6084, 997, 'smth', nil, nil], [6084, 998, 'smth', nil, nil]]" 

要正確EVAL它作爲一個數組我需要包裝帶引號的日期,我已經創建了一個正則表達式情況下,當日期是在陣列的中間:

(\s)\w{3},\s\d{2}\s\w{3}\s\d{4}\s\d{2}:\d{2}:\d{2}\s\w{3}\s\+00:00(,) 

並且當日期與]符號結束:

(\s)\w{3},\s\d{2}\s\w{3}\s\d{4}\s\d{2}:\d{2}:\d{2}\s\w{3}\s\+00:00(]) 

現在我想替換\1" '"\2"',""']"相應地,用什麼ruby方法可以完成我的任務?

回答

2

你的兩個正則表達式只有一個區別,最後一個字符是,]。所以加入他們在字符類使用[,\]]。並用它在你的紅寶石gsub()像這樣:

input = input.gsub(/(\s)(\w{3},\s\d{2}\s\w{3}\s\d{4}\s\d{2}:\d{2}:\d{2}\s\w{3}\s\+00:00)([,\]])/, " '\\2'\\3") 

我已經捕捉到你的約會對象分成兩組\\2並在三\\3組捕獲,]

捕獲組1沒有必要,但我沒有刪除它。如果刪除捕獲,那麼在上面的代碼中,分組將從\\2變換爲\\1\\3\\2

+0

不錯!謝謝! –

1

爲什麼不將日期轉換爲Date對象?

代碼

require 'date' 

regex = /\s(\w{3},\s\d{2}\s\w{3}\s\d{4}\s\d{2}:\d{2}:\d{2}\s\w{3}\s\+00:00)/ 
s = str.gsub(regex, " Date.parse('\\1')") 

然後

arr = eval(s) 

創建從字符串s陣列。注意正則表達式以'00:00'結尾。

演示

str = "[[5473, 992, 'smth', Tue, 25 Mar 2014 05:08:12 UTC +00:00, Fri, 07 Mar 2014 22:55:42 UTC +00:00], 
    [5473, 993, 'smth', Tue, 25 Mar 2014 14:38:05 UTC +00:00, Fri, 07 Mar 2014 22:57:33 UTC +00:00], 
    [6084, 994, 'smth', Mon, 24 Mar 2014 23:37:37 UTC +00:00, Mon, 24 Mar 2014 23:37:37 UTC +00:00], 
    [6084, 995, 'smth', nil, nil], 
    [6084, 996, 'smth', nil, nil], 
    [6084, 997, 'smth', nil, nil], 
    [6084, 998, 'smth', nil, nil]]" 

require 'awesome_print' 
ap eval(str.gsub(regex, " Date.parse('\\1')")) 
[ 
    [0] [ 
     [0] 5473, 
     [1] 992, 
     [2] "smth", 
     [3] #<Date: 2014-03-25 ((2456742j,0s,0n),+0s,2299161j)>, 
     [4] #<Date: 2014-03-07 ((2456724j,0s,0n),+0s,2299161j)> 
    ], 
    [1] [ 
     [0] 5473, 
     [1] 993, 
     [2] "smth", 
     [3] #<Date: 2014-03-25 ((2456742j,0s,0n),+0s,2299161j)>, 
     [4] #<Date: 2014-03-07 ((2456724j,0s,0n),+0s,2299161j)> 
    ], 
    [2] [ 
     [0] 6084, 
     [1] 994, 
     [2] "smth", 
     [3] #<Date: 2014-03-24 ((2456741j,0s,0n),+0s,2299161j)>, 
     [4] #<Date: 2014-03-24 ((2456741j,0s,0n),+0s,2299161j)> 
    ], 
    [3] [ 
     [0] 6084, 
     [1] 995, 
     [2] "smth", 
     [3] nil, 
     [4] nil 
    ], 
    [4] [ 
     [0] 6084, 
     [1] 996, 
     [2] "smth", 
     [3] nil, 
     [4] nil 
    ], 
    [5] [ 
     [0] 6084, 
     [1] 997, 
     [2] "smth", 
     [3] nil, 
     [4] nil 
    ], 
    [6] [ 
     [0] 6084, 
     [1] 998, 
     [2] "smth", 
     [3] nil, 
     [4] nil 
    ] 
] 
+0

感謝您的建議,但我不需要日期對象,因爲這些數據將發送到csv文件,無論如何+1會給您 –