简体   繁体   English

正则表达式在java中将字符串拆分为一半

[英]regex to split a string in half in java

we need help how to write the regex for string.split so we can split a string in half. 我们需要帮助如何为string.split编写正则表达式,这样我们就可以将字符串分成两半。

thanks. 谢谢。

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.split来做到这一点,但我只是使用这样的substring

    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]"

The above would split an odd-length String with part[1] one character longer than part[0] . 上面将分割一个奇数长度的Stringpart[1]part[0]长一个字符。 If you need it the other way around, then simply define mid = (s.length() + 1) / 2; 如果你需要mid = (s.length() + 1) / 2; ,那么只需定义mid = (s.length() + 1) / 2;


N -part split N部分split

You can also do something like this to split a string into N -parts: 您也可以执行以下操作将字符串拆分为N部分:

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;
}

Then you can do: 然后你可以这样做:

    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. 请注意,这有利于较早的部分来保存额外的字符,并且当部件的数量超过字符数时它也有效。


Appendix 附录

In the above code: 在上面的代码中:

  • ?: is the conditional operator, aka the ternary operator. ?:是条件运算符,也就是三元运算符。
  • / performs integer division. /执行整数除法。 1 / 2 == 0 . 1 / 2 == 0
  • % performs integer remainder operation. %执行整数余数运算。 3 % 2 == 1 . 3 % 2 == 1 Also, -1 % 2 == -1 . 另外, -1 % 2 == -1

References 参考

Related questions 相关问题

You really don't need a regex for this. 你真的不需要正则表达式。 Just use substring() . 只需使用substring()

int midpoint = str.length() / 2;
String firstHalf = str.substring(0, midpoint);
String secondHalf = str.substring(midpoint);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM