Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract portion of a line in ruby?

Tags:

regex

split

ruby

I have a line say

line = "start running at Sat April 1 07:30:37 2017"

and I want to extract

"Sat April 1 07:30:37 2017"

I tried this...

line = "start running at Sat April 1 07:30:37 2017"
if (line =~ /start running at/)
   line.split("start running at ").last
end

... but is there any other way of doing this?

like image 299
anu Avatar asked Dec 18 '25 21:12

anu


1 Answers

This is a way to extract, from an arbitrary string, a substring that represents a time in the given format. I've assumed there is at most one such substring in the string.

require 'time'

R = /
    (?:#{Date::ABBR_DAYNAMES.join('|')})\s
              # match day name abbreviation in non-capture group. space
    (?:#{Date::MONTHNAMES[1,12].join('|')})\s
              # match month name in non-capture group, space
    \d{1,2}\s # match one or two digits, space
    \d{2}:    # match two digits, colon
    \d{2}:    # match two digits, colon
    \d{2}\s   # match two digits, space
    \d{4}     # match 4 digits
    (?!\d)    # do not match digit (negative lookahead)
    /x        # free-spacing regex def mode
  # /
  #  (?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)\s
  #   (?:January|February|March|...|November|December)\s
  # \d{1,2}\s
  # \d{2}:
  # \d{2}:
  # \d{2}\s
  # \d{4}
  # (?!\d)
  # /x 

def extract_time(str)
  s = str[R]
  return nil if s.nil?
  (DateTime.strptime(s, "%a %B %e %H:%M:%S %Y") rescue nil) ? s : nil
end

str = "start eating breakfast at Sat April 1 07:30:37 2017"
extract_time(str)
  #=> "Sat April 1 07:30:37 2017" 

str = "go back to sleep at Cat April 1 07:30:37 2017"
extract_time(str)
  #=> nil

Alternatively, if there is a match against R, but Time#strptime raises an exception (meaning s is not a valid time for the given time format) one could raise an exception to advise the user.

like image 98
Cary Swoveland Avatar answered Dec 20 '25 11:12

Cary Swoveland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!