如何在Ruby中将字符串分成两个数组

时间:2014-09-29 06:59:36

标签: ruby arrays split

有没有办法将String#split删除的字符串提取到一个单独的数组中?

s = "This is a simple, uncomplicated sentence."
a = s.split( /,|\./ )  #=> [ "This is a simple", "uncomplicated sentence" ]
x = ... => should contain [ ",", "." ]

请注意,我需要使用的实际正则表达式比此示例复杂得多。

3 个答案:

答案 0 :(得分:2)

这样的东西?

a = s.scan( /,|\./ )

答案 1 :(得分:1)

如果你想要匹配的分隔符和两者之间的子串,就像在Stefan的评论中一样,那么你应该使用split来捕获。

"This is a simple, uncomplicated sentence."
.split(/([,.])/)
# => ["This is a simple", ",", " uncomplicated sentence", "."]

如果要将它们分成不同的数组,请执行以下操作:

a, x =
"This is a simple, uncomplicated sentence."
.split(/([,.])/).each_slice(2).to_a.transpose
a # => ["This is a simple", " uncomplicated sentence"]
x # => [",", "."]

a =
"This is a simple, uncomplicated sentence."
.split(/([,.])/)
a.select.with_index{|_, i| i.even?}
# => ["This is a simple", " uncomplicated sentence"]
a.select.with_index{|_, i| i.odd?}
# => [",", "."]

答案 2 :(得分:0)

试试这个:

a = s.split(/,/)[1..-1]