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"]
Try specifying a word boundary followed by one whitespace:
string = "alpha beta gamma delta"
p string.split(/\b\s/)
# ["alpha", "beta", " gamma", "delta"]
s.split(/(?<! ) /)
#=> ["alpha", "beta", " gamma", "delta"]
The regular expression matches each space that is not preceded by a space, (?<! ) being a negative lookbehind.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With