Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string by single spaces

Tags:

string

ruby

I have a string:

s = "alpha beta      gamma delta"

I'm trying to split this string with a single space as the delimiter without removing extra spaces to get this:

["alpha", "beta", "     gamma", "delta"]

Is there a way to do this?

The following does not give the results that I want:

s.split(" ") # => ["alpha", "beta", "gamma", "delta"]
s.split # => ["alpha", "beta", "gamma", "delta"]
like image 446
Zachary Goshen Avatar asked Feb 24 '26 07:02

Zachary Goshen


2 Answers

Try specifying a word boundary followed by one whitespace:

string = "alpha beta      gamma delta"
p string.split(/\b\s/)
# ["alpha", "beta", "     gamma", "delta"]
like image 187
Sebastian Palma Avatar answered Feb 26 '26 21:02

Sebastian Palma


s.split(/(?<! ) /)
  #=> ["alpha", "beta", "     gamma", "delta"]

The regular expression matches each space that is not preceded by a space, (?<! ) being a negative lookbehind.

like image 38
Cary Swoveland Avatar answered Feb 26 '26 22:02

Cary Swoveland