2011-01-22 75 views
8

我有一个字符串,它永远是至少一个数字,也可以前包含字母和/或之后数:分割字符串,保留数

"4" 
"Section 2" 
"4 Section" 
"Section 5 Aisle" 

我需要拆分像这样的字符串:

"4" becomes "4" 
"Section 2" becomes "Section ","2" 
"4 Aisle" becomes "4"," Aisle" 
"Section 5 Aisle" becomes "Section ","5"," Aisle" 

我该如何用Ruby 1.9.2来做到这一点?

回答

18

String#splitkeep any groups从结果数组中的分隔符regexp中删除。

parts = whole.split(/(\d+)/) 
2

如果你真的不想隔板中的空白,而你却想对/前后一致的手柄,使用此:

test = [ 
    "4", 
    "Section 2", 
    "4 Section", 
    "Section 5 Aisle", 
] 

require 'pp' 
pp test.map{ |str| str.split(/\s*(\d+)\s*/,-1) } 
#=> [["", "4", ""], 
#=> ["Section", "2", ""], 
#=> ["", "4", "Section"], 
#=> ["Section", "5", "Aisle"]] 

因此你总是可以做:

prefix, digits, suffix = str.split(/\s*(\d+)\s*/,-1) 
if prefix.empty? 
    ... 
end 

...而不是测试你的匹配或一些这样的长度。