Hi --
Hi --
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)
Hmm my \b at the end of my solution might have been a problem in some
edge cases, however I would suggest the usage of \z instead of $ and
the m switch. I fail to see why you put a \b at the beginning David,
would you mind to explain?
The idea was to start every scan at a \b. It's definitely not an
all-purpose solution to the problem anyway. For one thing, it doesn't
handle words of more than 50 characters -- which probably doesn't
matter, unless you're using it with a number less than 50:
str
=> "this is a string and i intend to split it up into little strings"
str.scan(/\b.{0,5}(?:$|\b)/m)
=> ["this ", "is a ", "", " and ", "i ", "", " to ", "split", " it ",
"up ", "into ", "", " ", "", ""]
Without the first \b you get:
["this ", "is a ", "", "tring", " and ", "i ", "", "ntend", " to ",
"split", " it ", "up ", "into ", "", "ittle", " ", "", "rings", ""]
So... further tweaking required
David
···
On Wed, 22 Jul 2009, Robert Dober wrote:
On 7/22/09, David A. Black <dblack@rubypal.com> wrote:
On Wed, 22 Jul 2009, Stuart Clarke wrote:
--
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\)