Ruby regex split at last symbol presence

I'm a bit obsessed with this, and I'm not 1.8 yet either, so I don't have a look.

I have a bunch of lines that might look like this:

"a/b/c/d/e/f 1/2/3"

      

to which I want to go:

"a/b/c/d/e" "f" "1/2" "3"

      

So, basically I want it to break on the last slash before the start of the space. I feel like I can do it fine, but the split always seems strange.

+2


source to share


2 answers


1.8 is missing lookbehind, not lookahead! All you need is:

str.split(/\/(?=[^\/]+(?: |$))| /)

      



This splitting pattern matches a) any forward slash followed by non-forward slash characters until the next space or end of the line, and b) any space.

+6


source


def foo s
   return [$1,$2] if s =~ /(.+)\/(\S)/
end

str = "a/b/c/d/e/f 1/2/3"
a = str.split /\s+/
a.collect { |e| foo e }.flatten

=> ["/a/b/c/d/e", "f", "1/2", "3"]

      



I broke the split and put it back together. You could, of course, shorten this if necessary.

+1


source







All Articles