Zachary Goshen
Zachary Goshen

Reputation: 91

Split a string by single spaces

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"]

Upvotes: 3

Views: 93

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110675

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

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

Upvotes: 2

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33420

Try specifying a word boundary followed by one whitespace:

string = "alpha beta      gamma delta"
p string.split(/\b\s/)
# ["alpha", "beta", "     gamma", "delta"]

Upvotes: 5

Related Questions