【问题标题】:Split string on the last occurrence of a character [closed]在最后一次出现字符时拆分字符串[关闭]
【发布时间】:2014-01-12 13:35:22
【问题描述】:

我有下面的字符串:

this sentence: should be: split after last colon: sentence

我想在最后一个冒号 (:) 上拆分上述字符串,以便生成的数组包含这两个元素:

["this sentence: should be: splited after last colon:", "sentence"]

【问题讨论】:

  • 问题不清楚。你想用冒号分割(保留冒号),还是用冒号后面的空格(丢弃空格)?
  • 你看问题了吗??

标签: ruby-on-rails ruby regex split


【解决方案1】:

试一试

str = "this sentence: should be: splited after last colon: sentence"
last_pos = str.rindex(/\:/)
arr = [str[0..last_pos].strip, str[last_pos + 1 .. str.length].strip]

=>["this sentence: should be: splited after last colon:", "sentence"] 

【讨论】:

    【解决方案2】:

    试试简单的代码:

    s = 'this sentence: should be: splited after last colon: sentence'
    s =~ /(.*):(.*)?/
    [ $1 << ':', $2 ]
    # => ["this sentence: should be: splited after last colon:", " sentence"]
    

    【讨论】:

      猜你喜欢
      • 2017-02-23
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 2014-01-21
      • 2017-04-29
      • 2019-01-06
      • 2011-01-28
      相关资源
      最近更新 更多