Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I split a string in ruby maintaining whitespaces in the split

Tags:

ruby

I have a string:

"hello\t    World\nbla" 

I would like to split it to:

["hello\t    ",
"World\n", 
"bla"] 

How would I do this in Ruby?

like image 474
Sam Saffron Avatar asked Jul 31 '09 05:07

Sam Saffron


People also ask

How do you split with whitespace?

You can split a String by whitespaces or tabs in Java by using the split() method of java. lang. String class. This method accepts a regular expression and you can pass a regex matching with whitespace to split the String where words are separated by spaces.

Does string split preserve order?

Yes, . split() always preserves the order of the characters in the string.

How do you split a string in Ruby?

split is a String class method in Ruby which is used to split the given string into an array of substrings based on a pattern specified. Here the pattern can be a Regular Expression or a string. If pattern is a Regular Expression or a string, str is divided where the pattern matches.


1 Answers

>> "hello\t    World\nbla".scan /\S+\s*/
=> ["hello\t    ", "World\n", "bla"]
like image 171
Gareth Avatar answered Oct 26 '22 02:10

Gareth