regex - Split string to equal length substrings in Java -


how split string "thequickbrownfoxjumps" substrings of equal size in java. eg. "thequickbrownfoxjumps" of 4 equal size should give output.

["theq","uick","brow","nfox","jump","s"] 

similar question:

split string equal-length substrings in scala

here's regex one-liner version:

system.out.println(arrays.tostring(     "thequickbrownfoxjumps".split("(?<=\\g.{4})") )); 

\g zero-width assertion matches position previous match ended. if there was no previous match, matches beginning of input, same \a. enclosing lookbehind matches position that's 4 characters along end of last match.

both lookbehind , \g advanced regex features, not supported flavors. furthermore, \g not implemented consistently across flavors support it. trick work (for example) in java, perl, .net , jgsoft, not in php (pcre), ruby 1.9+ or textmate (both oniguruma). javascript's /y (sticky flag) isn't flexible \g, , couldn't used way if js did support lookbehind.

i should mention don't recommend solution if have other options. non-regex solutions in other answers may longer, they're self-documenting; one's opposite of that. ;)

also, doesn't work in android, doesn't support use of \g in lookbehinds.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -