2

重複の可能性:
文字列をリストに分割しますが、分割パターンは維持します

"hello world, I am the universe".partition(/I am/)
    #=> ["hello world, ", "I am", " the universe"]

この出力を持つルビーの方法は何ですか? より複雑な文字列にも注意してください。

#=> ["hello world, ", "I am the universe"]

複雑:

"hello world, I am the universe, I am the world".some_partitioning_function(/I am/)
#=>["hello world, ", "I am the universe, ", "I am the world"]
4

4 に答える 4

1

メソッドがありませんか?独自の追加:

class String
  def some_partitioning_function(delim_str)
    split(delim_str).map.with_index do |str, i|
      i > 0 ? delim_str + str : str
    end
  end
end

"hello world, I am the universe, I am the world".some_partitioning_function('I am')

 => ["hello world, ", "I am the universe, ", "I am the world"] 
于 2012-09-10T19:53:36.133 に答える
0
"hello world, I am the universe".split(/,\s(?=I\sam)/,2)

それは本当にあなたが探していたものですか?

于 2012-09-10T14:14:28.620 に答える
0

このタスクは正規表現で解決する必要があると思います。私の正規表現はあまりきれいではありません。後で修正できるかもしれません。

reg = /(.+?(?=I\sam))(I\sam.+?(?=I\sam)|I\sam.+$)/
str = "hello world, I am the universe, I am the world, I am the earth"

str.scan(reg).flatten
=> ["hello world, ", "I am the universe, ", "I am the world, ", "I am the earth"]
于 2012-09-10T20:33:45.033 に答える
0

@pwned がリンクした質問の複製ではないとおっしゃいましたが、そのようなものです。Ruby を少しいじる必要があるだけです。

s = "hello world, I am the universe, I am the world" # original string
a = s.split(/(I am)/) 
#=> ["hello world, ", "I am", " the universe, ", "I am, " the world"]

ここで、上記のリンクされた SO の質問で提案されているソリューションを使用します。ただし、配列の最初の要素はスキップします。

sliced = a[1..-1].each_slice(2).map(&:join) 
#=> ["I am the universe, ", "I am the world"]

これを、除外した配列要素と結合します。

final = [a[0]] + sliced 
#=> ["hello world, ", "I am the universe, ", "I am the world"]

これを次のようなメソッドにスローします。

class String
  def split_and_include(words)
    s = self.split(/(#{words})/)
    [s[0]] + s[1..-1].each_slice(2).map(&:join)
  end
end 

"You all everybody. You all everybody.".split_and_include("all")
#=> ["You ", "all everybody. You ", "all everybody."]

これを行うためのよりクリーンな方法があると確信しており、より簡単な方法を発見したら回答を更新します。

于 2012-09-10T16:21:29.960 に答える