HUX布斯
无需使用正则表达式。相反,您可以递归地构建头部字符串列表并返回尾部。import java.util.*;public class StringChunker { public static void main(String[] args) { String str = "abcdefghijklm"; System.out.println(Arrays.toString(chunk(str, 4))); // [abcd, efgh, ijkl, m] System.out.println(Arrays.toString(chunk(str, 4, true))); // [a, bcde, fghi, jklm] } public static String[] chunk(String str, int size) throws IllegalArgumentException { return chunk(str, size, false); } public static String[] chunk(String str, int size, boolean reverse) throws IllegalArgumentException { return chunk(str, size, reverse, new ArrayList<String>()); } private static String[] chunk(String str, int size, boolean reverse, List<String> chunks) throws IllegalArgumentException { if (size < 1) { throw new IllegalArgumentException("size must be greater than 0"); } if (str.length() < size) { if (reverse) { chunks.add(0, str); // Reverse adds to the front of the list } else { chunks.add(str); // Add to the end of the list } return chunks.toArray(new String[chunks.size()]); // Convert to an array } else { String head, tail; if (reverse) { head = str.substring(str.length() - size, str.length()); tail = str.substring(0, str.length() - size); chunks.add(0, head); } else { head = str.substring(0, size); tail = str.substring(size); chunks.add(head); } return chunk(tail, size, reverse, chunks); } }}