简体   繁体   中英

Regex to split string into verying size chunks

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM