Ruby使用引号将日期包装在字符串中

时间:2014-03-25 17:27:38

标签: ruby regex replace

我有一个来自文件的字符串,如下所示:

"[[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]]"

要正确地将其作为数组进行评估我需要用引号括起日期,我已经为日期位于数组中间的情况创建了一个正则表达式:

(\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方法可以完成我的任务?< / p>

2 个答案:

答案 0 :(得分: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组\\2,并在第3组,中抓取]\\3

捕捉第1组并非必要,但我没有删除它。如果您删除了捕获,则上述代码中的分组将从\\2转移到\\1\\3转移到\\2

答案 1 :(得分: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
    ]
]