嗨,我是 Ruby 和正则表达式的新手。我正在尝试使用正则表达式从日期中删除月份或日期中的任何零,日期格式为“02/02/1980”=>“2/2/1980”
def m_d_y
strftime('%m/%d/%Y').gsub(/0?(\d{1})\/0?(\d{1})\//, $1 + "/" + $2 + "/" )
end
这个正则表达式有什么问题?
谢谢。
"02/02/1980".gsub(/\b0/, '') #=> "2/2/1980"
\b
是字边界的零宽度标记,因此\b0
在零之前不能有数字。
您可以简单地删除以斜线结尾的部分中的 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
当你可以做到这一点时,为什么还要使用正则表达式呢?
require "date"
class Date
def m_d_y
[mon, mday, year].join("/")
end
end
尝试/(?<!\d)0(\d)/
"02/02/1980".gsub(/(?<!\d)0(\d)/,$1)
=> "2/2/1980"
问题是它与有效日期不匹配,因此您的替换将破坏有效字符串。修理:
正则表达式:(^|(?<=/))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,然后调试你的正则表达式。