有没有办法将String#split
删除的字符串提取到一个单独的数组中?
s = "This is a simple, uncomplicated sentence."
a = s.split( /,|\./ ) #=> [ "This is a simple", "uncomplicated sentence" ]
x = ... => should contain [ ",", "." ]
请注意,我需要使用的实际正则表达式比此示例复杂得多。
答案 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]