Split string by multiple delimiters Split string by multiple delimiters ruby ruby

Split string by multiple delimiters


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.