Ryzal Yusoff
Ryzal Yusoff

Reputation: 1047

Extract Date from string ruby

I have this string :

Rep. Barletta, Lou [R-PA-11] (Introduced 06/04/2015)

And I want to extract the date which is "06/04/2015". How do i do this in ruby? I have tried to do something like this:

str[-1..-11]

but didnt work. Any suggestion? Thanks!

Upvotes: 0

Views: 2631

Answers (5)

Cary Swoveland
Cary Swoveland

Reputation: 110675

@steenslag's answer looks for valid dates (unlike the other answers), but could still be tripped up:

str = "The first 10 may go 15/15/2015 with Lou (Introduced 06/04/2015)"
Date.parse(str)
  #=> #<Date: 2015-05-10 ((2457153j,0s,0n),+0s,2299161j)>

To ensure the date is in the specified format, you could do the following:

require 'date'

def extract_date(str, fmt)
  a = str.each_char
         .each_cons(10)
         .find { |a| Date.strptime(a.join, fmt) rescue nil }
  a ? a.join : nil
end

For str as above:

extract_date(str, '%d/%m/%Y')
  #=> "06/04/2015"

A second example:

extract_date("15/15/2015", '%d/%m/%Y')
  #=> nil

Upvotes: 0

Piccolo
Piccolo

Reputation: 1666

str = "Rep. Barletta, Lou [R-PA-11] (Introduced 06/04/2015)"
str.match(/(\d{2}\/\d{2}\/\d{4})/)[0]
#=> "06/04/2015"

This code matches anything that's in the format of 2 numbers/2 numbers/4 numbers and returns it.

If there's a possibility of having XX/XX/XXXX somewhere else in the string, I'd probably use the following code instead:

str = "Rep. Barletta, Lou [R-PA-11] (Introduced 06/04/2015)"
str.match(\(Introduced (\d{2}\/\d{2}\/\d{4})\)$)[0]
#=> "06/04/2015"

This searches for (Introduced XX/XX/XXXX) and grabs the date from that in particular.

Upvotes: 3

steenslag
steenslag

Reputation: 80065

Date has a parse method, which happens to just work.

require 'date'

str = "Rep. Barletta, Lou [R-PA-11] (Introduced 06/04/2015)"
p d = Date.parse(str) # => #<Date: 2015-04-06 ((2457119j,0s,0n),+0s,2299161j)>

Upvotes: 2

Jim Flood
Jim Flood

Reputation: 8457

I agree with Piccolo's comment. Here is a simple regular expression you can try in irb. I recommend experimenting in irb to learn some rudimentary Ruby regular expressions.

For example, /.+([0-9]{2}\/[0-9]{2}\/[0-9]{4}).+/ looks for anything followed by two digits, slash, two digits, slash, four digits, then anything:

$ irb
2.2.0 :001 > s='Rep. Barletta, Lou [R-PA-11] (Introduced 06/04/2015)'
2.2.0 :009 > /.+([0-9]{2}\/[0-9]{2}\/[0-9]{4}).+/ =~ s && $1
 => "06/04/2015" 
2.2.0 :010 > 

Upvotes: 1

lumos0815
lumos0815

Reputation: 4316

str[-11..-2] if the position of the date does not change

Upvotes: 1

Related Questions