regex - How do I keep the split token in the second part of what was split in Ruby?


Keywords:ruby 


Question: 

In Ruby, how do you split a stirng and keep the token with which you are splitting on in the second part of the result of the split? I have

line.split(/(?<=#{Regexp.escape(split_token)})/)

But the token is getting merged into the first part of teh split and I want it in the second part

2.4.0 :004 >   split_token = "aaa"
 => "aaa"
2.4.0 :005 > line = "bbb aaa ccc"
 => "bbb aaa ccc"
2.4.0 :006 > line.split(/(?<=#{Regexp.escape(split_token)})/)
 => ["bbb aaa", " ccc"]

2 Answers: 

Changing lookbehind ((?<=) to lookahead ((?=) seems to do the trick:

split_token = "aaa"
line = "bbb aaa ccc"
line.split(/(?=#{Regexp.escape(split_token)})/)
# => ["bbb ", "aaa ccc"]

This just changes the split point to before the token rather than after it.

 

Another possibility is to use slice_before :

line.split.slice_before('aaa').map{|s| s.join(' ')}