问题描述
我们需要帮助如何为string.split编写正则表达式,这样我们就可以将字符串分成两半。
we need help how to write the regex for string.split so we can split a string in half.
谢谢。
推荐答案
没有明显的正则表达式模式可以做到这一点。 可能可以使用 String.split
执行此操作,但我只使用 substring
像这样:
There's no obvious regex pattern that would do this. It may be possible to do this with String.split
, but I'd just use substring
like this:
String s = "12345678abcdefgh";
final int mid = s.length() / 2;
String[] parts = {
s.substring(0, mid),
s.substring(mid),
};
System.out.println(Arrays.toString(parts));
// "[12345678, abcdefgh]"
以上将拆分奇数长度字符串
part [1]
一个字符长于 part [0]
。如果您需要反过来,那么只需定义 mid =(s.length()+ 1)/ 2;
The above would split an odd-length String
with part[1]
one character longer than part[0]
. If you need it the other way around, then simply define mid = (s.length() + 1) / 2;
您还可以执行以下操作将字符串拆分为 N - 部分:
You can also do something like this to split a string into N-parts:
static String[] splitN(String s, final int N) {
final int base = s.length() / N;
final int remainder = s.length() % N;
String[] parts = new String[N];
for (int i = 0; i < N; i++) {
int length = base + (i < remainder ? 1 : 0);
parts[i] = s.substring(0, length);
s = s.substring(length);
}
return parts;
}
然后你可以这样做:
String s = "123456789";
System.out.println(Arrays.toString(splitN(s, 2)));
// "[12345, 6789]"
System.out.println(Arrays.toString(splitN(s, 3)));
// "[123, 456, 789]"
System.out.println(Arrays.toString(splitN(s, 5)));
// "[12, 34, 56, 78, 9]"
System.out.println(Arrays.toString(splitN(s, 10)));
// "[1, 2, 3, 4, 5, 6, 7, 8, 9, ]"
请注意,这有利于早期部分保存额外字符,当部件数量超过字符数时,它也有效。
Note that this favors the earlier parts to hold the extra characters, and it also works when the number of parts is more than the number of characters.
在上面的代码中:
-
?:
是条件运算符,也就是三元运算符。 -
/
执行整数除法。1/2 == 0
。 -
%
执行整数余数运算。3%2 == 1
。此外,-1%2 == -1
。
?:
is the conditional operator, aka the ternary operator./
performs integer division.1 / 2 == 0
.%
performs integer remainder operation.3 % 2 == 1
. Also,-1 % 2 == -1
.
- JLS 15.25 Conditional Operator ?:
- JLS 15.17.2 Division Operator /
- JLS 15.17.3 Remainder Operator %
- How does the ternary operator work?
- Why does (360 / 24) / 60 = 0 … in Java
这篇关于正则表达式在java中将字符串拆分为一半的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!