How to find dates in a csv file using a regular expression and store in an array [using Ruby]?

The correct one liner is: File. Open('yourfile. Csv').read.

Scan /\d{2}\/\d{2}\/\d{2} and by the way \d{2} is so much nicer than \d\d and here's why: you can see the 2. \d{2} reads like "2 digit number" (once you're used to it) if you want to change it to 1 or 2 digits you can do {1,2}.

The correct one liner is: File. Open('yourfile. Csv').read.

Scan /\d{2}\/\d{2}\/\d{2}/ and by the way \d{2} is so much nicer than \d\d and here's why: you can see the 2. \d{2} reads like "2 digit number" (once you're used to it) if you want to change it to 1 or 2 digits you can do {1,2}.

This is much easier to read. Out of curiosity, why use File. Open instead of CSV.

Open? – Sean Lerner Nov 16 at 16:14 1 File. Read puts the entire contents into a string.

CSV builds arrays. – pguardiario Nov 16 at 22:56.

Dates = File. Open('yourfile. Csv').

Each_line do |line| if m = line. Match(/^\d\d\/\d\d\/\d\d/) dates. Push m end end puts dates BTW.

I am sure someone could write this as a one-liner, but this might be a little easier to understand for someone new to Ruby. I making these assumptions: All dates are of the format mm/dd/yy. All dates that you want in the array are at the start of each line.

You don't need to verify that it is a valid date.

Ah, someone already did write it as one line before I could even finish typing the answer. – Jake W Nov 16 at 7:28.

You could get a first approximation with this: dates = CSV. Open('x. Csv').

Map{|r| r. Select { |x| x =~ /\d\d\/\d\d\/\d\d/ } }. Flatten and then, if needed, scan through the elements of dates to make sure numbers are in the proper ranges (so that you don't accidentally include a date that claims to be Feb 31 2001).

If you want to check the format, you could use DateTime. Strptime and catch ArgumentErrors: clean = dates. Select do |d| begin # I'm guessing on the date format.DateTime.

Strptime(d, '%m/%d/%y') rescue ArgumentError nil end end.

This is exactly what I wanted but couldn't figure out! Thanks! – Sean Lerner Nov 16 at 7:31 sorry mu, I didn't mean to imply that you were incorrect, just that it could be more concise.

– pguardiario Nov 16 at 10:26.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions