Kashiftufail
Kashiftufail

Reputation: 10885

How can I split this string?

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.

Upvotes: 4

Views: 159

Answers (2)

Bozhidar Batsov
Bozhidar Batsov

Reputation: 56595

Not very pretty, but gets the job done:

a.scan(/(\S+)|(\[.+?\])/).map(&:compact).flatten

Later I noticed that the groups I used were not necessary at all and without them the solution could be simplified to:

a.scan(/\S+|\[.+?\]/)

Upvotes: 4

sawa
sawa

Reputation: 168101

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+/)

Upvotes: 6

Related Questions