gpt4 book ai didi

ruby - 如何在 Ruby 中返回两个字符串之间的字符串的子字符串?

转载 作者:数据小太阳 更新时间:2023-10-29 06:23:36 25 4
gpt4 key购买 nike

如何在 Ruby 中返回字符串的两个字符串标记之间的字符串?

例如我有:

  • 输入字符串
  • str1_markerstring
  • str2_markerstring

想要做这样的事情:

input_string.string_between_markers(str1_markerstring, str2_markerString)

示例文本:

s
# => "Charges for the period 2012-01-28 00:00:00 to 2012-02-27 23:59:59:<br>\nAny Network Cap remaining: $366.550<br>International Cap remaining: $0.000"
str1_markerstring
# => "Charges for the period"
str2_markerstring
# => "Any Network Cap"
s[/#{str1_markerstring}(.*?)#{str2_markerstring}/, 1]
# => nil # IE DIDN'T WORK IN THIS CASE

使用 Ruby 1.9.3。

最佳答案

input_string = "blahblahblahSTARTfoofoofooENDwowowowowo"
str1_markerstring = "START"
str2_markerstring = "END"

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

或者把它放在一个方法中:

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"

关于ruby - 如何在 Ruby 中返回两个字符串之间的字符串的子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9661478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com