Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I split this string?

Tags:

ruby

I have this string:

a = "hy what are you doing [Zoho Reports] will you like? [Zoho Books] reply"

and I want to split it so the result is like this:

hy
what
are
you
doing
[Zoho Reports]
will
you
like?
[Zoho Books]
reply

How can I loop that string to achieve those results? I'm currently doing this:

a.split("")

but it splits up "[Zoho Reports]" into "[Zoho" and "Reports]", which I don't want.

like image 433
Kashiftufail Avatar asked Dec 27 '22 16:12

Kashiftufail


1 Answers

In this case, you should use scan instead of split because it is easier to characterize what you want rather than what you want to throw out.

Similar to Bozhidar's answer, but you don't need the complication.

a.scan(/\[.*?\]|\S+/)
like image 192
sawa Avatar answered Jan 11 '23 08:01

sawa