将字符串拆分为数组的n长度元素[复制]

时间:2022-04-29 15:41:01

This question already has an answer here:

这个问题在这里已有答案:

How would I split a string into equal parts using String.split() provided the string is full of numbers? For the sake of example, each part in the below is of size 5.

如果字符串充满数字,我如何使用String.split()将字符串拆分成相等的部分?例如,下面的每个部分的大小为5。

"123" would be split into "123"
"12345" would be split into "12345"
"123451" would be split into "12345" and "1"
"123451234512345" would be split into "12345", "12345" and "12345"
etc

These are to be put in an array:

这些将放在一个数组中:

String myString = "12345678";
String[] myStringArray = myString.split(???);
//myStringArray => "12345", "678";

I'm just unsure the regex to use, nor how to separate it into equal sized chunks.

我只是不确定要使用的正则表达式,也不确定如何将它分成相同大小的块。

1 个解决方案

#1


7  

You can try this way

你可以试试这种方式

String input = "123451234512345";
String[] pairs = input.split("(?<=\\G\\d{5})");
System.out.println(Arrays.toString(pairs));

Output:

[12345, 12345, 12345]

This regex uses positive look behind mechanism (?<=...) and \\G which represents "previous match - place where previously matched string ends, or if it doesn't exist yet (when we just started matching) ^ which is start of the string".

这个正则表达式使用正向后看机制(?<= ...)和\\ G表示“上一个匹配 - 先前匹配的字符串结束的地方,或者它是否还不存在(当我们刚刚开始匹配时)^这是字符串的开头“。

So regex will match any place that has five digits before it and before this five digits previously matched place we split on.

所以正则表达式将匹配任何前面有五位数的地方,并且在之前匹配的五位数字之前我们分开。

#1


7  

You can try this way

你可以试试这种方式

String input = "123451234512345";
String[] pairs = input.split("(?<=\\G\\d{5})");
System.out.println(Arrays.toString(pairs));

Output:

[12345, 12345, 12345]

This regex uses positive look behind mechanism (?<=...) and \\G which represents "previous match - place where previously matched string ends, or if it doesn't exist yet (when we just started matching) ^ which is start of the string".

这个正则表达式使用正向后看机制(?<= ...)和\\ G表示“上一个匹配 - 先前匹配的字符串结束的地方,或者它是否还不存在(当我们刚刚开始匹配时)^这是字符串的开头“。

So regex will match any place that has five digits before it and before this five digits previously matched place we split on.

所以正则表达式将匹配任何前面有五位数的地方,并且在之前匹配的五位数字之前我们分开。