我想浏览文件中的每一行,并找到mm/dd/yyyy
格式的日期。我尝试了scan
和match
,但我认为他们并不适合我。我还能尝试什么?我能看到样品你会怎么做(使用正则表达式)?
答案 0 :(得分:0)
测试代码:
file_data = "with a date 01/02/1900 \n without a date in line\n"
file_data.each_line do |l|
dt = l.scan(/(\d{2}\/\d{2}\/\d{4})/).flatten.first
puts "Line: #{l} #{dt ? 'with' : 'without'} a date #{dt} in it."
end
结果:
Line: with a date 01/02/1900
with a date 01/02/1900 in it.
Line: without a date in line
without a date in it.
正则表达式可能无法验证30/31天和闰年的月份。我只是想帮助你进一步研究这个话题。