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

后端 未结 3 1940
梦如初夏
梦如初夏 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:29

    input_string = "blahblahblahSTARTfoofoofooENDwowowowowo"
    str1_markerstring = "START"
    str2_markerstring = "END"
    
    input_string[/#{str1_markerstring}(.*?)#{str2_markerstring}/m, 1]
    #=> "foofoofoo"
    

    or to put it in a method:

    class String
      def string_between_markers marker1, marker2
        self[/#{Regexp.escape(marker1)}(.*?)#{Regexp.escape(marker2)}/m, 1]
      end
    end
    
    "blahblahblahSTARTfoofoofooENDwowowowowo".string_between_markers("START", "END")
    #=> "foofoofoo"
    

提交回复
热议问题