在数字上拆分字符串,保留数字

时间:2011-01-22 05:32:41

标签: ruby regex

我有一个字符串,它总是至少是一个数字,但也可以在数字之前和/或之后包含字母:

"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执行此操作?

2 个答案:

答案 0 :(得分:18)

String#splitkeep any groups来自结果数组中的分隔符regexp。

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

答案 1 :(得分: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

...而不是测试你的比赛的长度或其他一些。