Regex to split a string in half in java

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

thanks.

+4
source share
2 answers

There is no obvious regex pattern to do this. Perhaps this can be done using String.split , but I would just use substring as follows:

  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 the odd length of String by part[1] one character longer than part[0] . If you need it the other way around, just define mid = (s.length() + 1) / 2;


split n-piece

You can also do something similar to split the 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 allows earlier parts to hold extra characters, and also works when the number of parts is greater than the number of characters.


application

In the above code:

  • ?: is a conditional statement called a ternary operator.
  • / performs integer division. 1 / 2 == 0 .
  • % performs an integer remainder operation. 3 % 2 == 1 . In addition, -1 % 2 == -1 .

References

Related Questions

+21
source

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); 
+8
source

Source: https://habr.com/ru/post/1315715/


All Articles