I want to go through each line in a file and find a date in format mm/dd/yyyy
. I tried scan
and match
, but I don't think they are working for me. What else can I try? Can I see samples how would you guys do it (using regular expressions)?
Asked
Active
Viewed 232 times
1
-
Why is `match` not working? – sawa Aug 01 '14 at 01:31
-
Will single-digit months and days have leading zeros? – Cary Swoveland Aug 01 '14 at 01:35
-
Ariam, you may wish to edit your question to include a small part of a typical file and also how you used `scan` and/or `match`. – Cary Swoveland Aug 01 '14 at 02:20
1 Answers
0
Test Code:
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
Result:
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.
The regexp may not validate months with 30/31 days and leap years. I just want to help you to study further on this topic.

Jaugar Chang
- 3,176
- 2
- 13
- 23