按空格和数字分割字符串Ruby

时间:2020-08-10 12:11:26

标签: ruby split

如何按空格和特定数字分割字符串?我的字符串看起来像

PID55688.00976 1
PID66854.76557 2
PID88774.23455 3
PID66843.99754 1
PID66800.00764 3

我想按空格和数字3分割字符串

代码 str.split(/\s3/)不会拆分任何内容。

3 个答案:

答案 0 :(得分:1)

我会做这样的事情:

string = <<-STRING
PID55688.00976 1
PID66854.76557 2
PID88774.23455 3
PID66843.99754 1
PID66800.00764 3
STRING

string.scan(/(\w+\.\w+ \w+)\n/).flatten
#=> [["PID55688.00976 1"], ["PID66854.76557 2"], ["PID88774.23455 3"], ["PID66843.99754 1"], ["PID66800.00764 3"]]

答案 1 :(得分:1)

这将产生OP在@spickermann答案的注释中描述的预期输出:

string = <<-STRING
PID55688.00976 1
PID66854.76557 2
PID88774.23455 3
PID66843.99754 1
PID66800.00764 3
STRING

string.split(/ 3\n/).map{|substring| (substring+" 3").split(/\n/)}

但是OP的预期答案中有一些错别字,因为数组中没有逗号或引号。所以我可能会误解。

答案 2 :(得分:0)

假设

[["PID55688.00976 1", "PID66854.76557 2", "PID88774.23455 3"],
 ["PID66843.99754 1", "PID66800.00764 3"]] 

是想要的返回值,可以这样写:

string.split(/\r?\n/).slice_after { |s| s.end_with?(' 3') }.to_a

参见 Enumerable#slice_after 和 String#end_with?。