I want to split a string by whitespaces, ,
and '
using a single ruby command.
word.split
will split by white spaces;
word.split(",")
will split by ,
;
word.split("\'")
will split by '
.
How to do all three at once?
word = "Now is the,time for'all good people"
word.split(/[\s,']/)
=> ["Now", "is", "the", "time", "for", "all", "good", "people"]
Regex.
"a,b'c d".split /\s|'|,/
# => ["a", "b", "c", "d"]
You can use a combination of the split
method and the Regexp.union
method like so:
delimiters = [',', ' ', "'"]
word.split(Regexp.union(delimiters))
# => ["Now", "is", "the", "time", "for", "all", "good", "people"]
You can even use regex patters in the delimiters.
delimiters = [',', /\s/, "'"]
word.split(Regexp.union(delimiters))
# => ["Now", "is", "the", "time", "for", "all", "good", "people"]
This solution has the advantage of allowing totally dynamic delimiters or any length.
Here is another one :
word = "Now is the,time for'all good people"
word.scan(/\w+/)
# => ["Now", "is", "the", "time", "for", "all", "good", "people"]
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