Reputation: 1328
I'm trying to break a string into chunks of varying sizes, creating a "wave" of words such as:
the
cat sat
on the mat the
cat sat on the mat the
cat sat on the
mat the
cat
As words have varying lengths I want to split on the nearest space.
I may be trying to do too much with one line. However I don't like the idea of loops. I've started with this:
/.{5}\w*/g
I've tried adding () around and adding {} but can't quite get the hang of regexes. Is this possible to do? Or will there involve some sort of loop?
Upvotes: 0
Views: 140
Reputation: 626758
I think there is something that can be done even with a regex, BUT a lot depends on the input string. Also, you will have to think about how to arrange chunks, whether to trim or not, how to pad, etc. so just a regex won't do.
This regex pattern:
((?:[^\s]+(?:\s|$)){1,20})
can yield something similar to what you are looking for in the following string:
the cat sat on the mat the cat sat on the mat the cat sat on the mat
. It works because of additional spaces right where the breakdown should occur.
the
cat sat
on the mat the
cat sat on the mat the
cat sat on the
mat
See demo.
Upvotes: 1