I'd like to split the string into substrings which has 20 chars (or less for the tail). Is there some library or I need to make the class for that?
Asked
Active
Viewed 3,135 times
1
-
2Just use substring. There may *be* a library function somewhere which does this, but it's sufficiently easy to do that I wouldn't spend too long looking for it. – Jon Skeet Sep 20 '13 at 11:33
-
%) apparently, however with `groovy` it could be even easier. Will wait for other replies – Archer Sep 20 '13 at 11:34
2 Answers
10
you should use :
s.split("(?<=\\G.{20})");
\G
is a zero-width assertion that matches the position where the previous match ended. If there was no previous match, it matches the beginning of the input, the same as \A
. The enclosing lookbehind matches the position that's 20 characters along from the end of the last match.

Melih Altıntaş
- 2,495
- 1
- 22
- 35
4
Or, with Groovy you could do:
assert 'abcdefghij'.toList().collate( 3 )*.join() == ['abc', 'def', 'ghi', 'j']

tim_yates
- 167,322
- 27
- 342
- 338