How to return the substring of a string between two strings in Ruby?

后端 未结 3 1939
梦如初夏
梦如初夏 2020-12-08 04:22

How would I return the string between two string markers of a string in Ruby?

For example I have:

  • input_string
  • str1_marker
3条回答
  •  感动是毒
    2020-12-08 04:41

    Here's some alternate ways to do what you want, that are how I'd go about it:

    s = "Charges for the period 2012-01-28 00:00:00 to 2012-02-27 23:59:59:
    \nAny Network Cap remaining: $366.550
    International Cap remaining: $0.000" # => "Charges for the period 2012-01-28 00:00:00 to 2012-02-27 23:59:59:
    \nAny Network Cap remaining: $366.550
    International Cap remaining: $0.000" dt1, dt2 = /period (\S+ \S+) to (\S+ \S+):/.match(s).captures # => ["2012-01-28 00:00:00", "2012-02-27 23:59:59"] dt1 # => "2012-01-28 00:00:00" dt2 # => "2012-02-27 23:59:59"

    This is using "period" and "to" and the trailing ":" to mark the begin and end of the range to be searched for, and grabbing the non-whitespace characters that signify the date and time in each datetime stamp.

    Alternately, using "named-captures" predefines the variables:

    /period (?\S+ \S+) to (?\S+ \S+):/ =~ s  # => 16
    dt1                                                # => "2012-01-28 00:00:00"
    dt2                                                # => "2012-02-27 23:59:59"
    

    From that point, if you want to break down the values returned you could parse them as dates:

    require 'date'
    d1 = DateTime.strptime(dt1, '%Y-%m-%d %H:%M:%S')  # => #
    d1.month                                          # => 1
    d1.day                                            # => 28
    

    Or you could even use sub-captures:

    matches = /period (?(?\S+) (?\S+)) to (?(?\S+) (?\S+)):/.match(s)
    matches # => #
    matches['dt1']   # => "2012-01-28 00:00:00"
    matches['date1'] # => "2012-01-28"
    matches['time2'] # => "23:59:59"
    

    This is all documented in the Regexp documentation.

提交回复
热议问题