Reputation: 91
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
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
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