开发者

regex to split a string in half in java

we need help how to write the regex for string.split so we can s开发者_如何转开发plit a string in half.

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 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]. If you need it the other way around, then simply define mid = (s.length() + 1) / 2;


N-part split

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

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.
  • % performs integer remainder operation. 3 % 2 == 1. Also, -1 % 2 == -1.

References

  • JLS 15.25 Conditional Operator ?:
  • JLS 15.17.2 Division Operator /
  • JLS 15.17.3 Remainder Operator %

Related questions

  • How does the ternary operator work?
  • Why does (360 / 24) / 60 = 0 … in Java


You really don't need a regex for this. Just use substring().

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜