Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string by multiple delimiters

Tags:

string

split

ruby

I want to split a string by whitespaces, , and ' using a single ruby command.

  1. word.split will split by white spaces;

  2. word.split(",") will split by ,;

  3. word.split("\'") will split by '.

How to do all three at once?

like image 242
Karan Verma Avatar asked Oct 22 '13 04:10

Karan Verma


4 Answers

word = "Now is the,time for'all good people"
word.split(/[\s,']/)
 => ["Now", "is", "the", "time", "for", "all", "good", "people"] 
like image 125
Cary Swoveland Avatar answered Oct 19 '22 15:10

Cary Swoveland


Regex.

"a,b'c d".split /\s|'|,/
# => ["a", "b", "c", "d"]
like image 30
oldergod Avatar answered Oct 19 '22 14:10

oldergod


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.

like image 32
James Stonehill Avatar answered Oct 19 '22 15:10

James Stonehill


Here is another one :

word = "Now is the,time for'all good people"
word.scan(/\w+/)
# => ["Now", "is", "the", "time", "for", "all", "good", "people"]
like image 24
Arup Rakshit Avatar answered Oct 19 '22 15:10

Arup Rakshit