How can I split this line?

I have this line:

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

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

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

How can I loop this line to achieve these results? I am doing this now:

 a.split("") 

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

+4
source share
2 answers

Not very pretty, but it does its job:

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

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

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

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 away.

Similar to Bozidar’s answer, but you don’t need to complicate.

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

Source: https://habr.com/ru/post/1438286/


All Articles