tags:

views:

111

answers:

2

hi,

we need help how to write the regex for string.split so we can split a string in half.

thanks.

+13  A: 

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

Related questions

polygenelubricants
+1 for managing to type a full answer in under a minute! Makes me feel slow...
Justin Ardini
@polygenelubricants: +1 for going above and beyond by including N-splits and reference links. Great answer!
Justian Meyer
+6  A: 

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);
Justin Ardini
+1, for a short, simple, concise answer. Let the OP respond and clarify the question if a more complex solution is required.
camickr