From: "David A. Black" Date: 2009-07-22T10:00:56+09:00 Subject: Re: String spliting and inclusion Hi -- On Wed, 22 Jul 2009, Stuart Clarke wrote: > Hi all, > > I am having trouble working out some logic for my problem. I basically > have a long string (320 characters) and I want to split into smaller > strings no longer than 50 characters in length. At present I have the > following regex: > > data = "big long string" > > puts data.scan(/{50}/) > > This nicely breaks up the string however there are a few problems with > it, including: > > It only outputs 50 character chunks, therefore when it gets to the end > and only 20 characters remain it misses them off the output (it outputs > 6 50 characters strings and ignores the remaining 20) > > This regex also splits up words, which is something I don't want. I want > a script to count to 50 and when it gets there, go backwards to find > some white space and split it at that point, therefore not breaking up a > word. As a result a number of sub strings of various sizes will be > created all less than 50 chars. > > I hope this makes sense, to summarise I want to break up a string into a > max of 50 characters without breaking up words. Try this. I don't guarantee robustness. str.scan(/\b.{0,50}(?:$|\b)/m) David -- David A. Black / Ruby Power and Light, LLC Ruby/Rails consulting & training: http://www.rubypal.com Now available: The Well-Grounded Rubyist (http://manning.com/black2) Training! Intro to Ruby, with Black & Kastner, September 14-17 (More info: http://rubyurl.com/vmzN)