[Solved] Java – Convert a string of multiple characters to just a string of numbers


Solution:

String s = "(1,2)-(45,87)";
String[] splitted = s.replaceFirst("\\D+", "").split("\\D+"); // Outputs: [1, 2, 45, 87]

Explanation:

\\D++ – means one or more non-digit characters

s.replaceFirst("\\D+", "") – this is needed to avoid storing empty String at the first index of splitted array (if there is a “delimited” at the first index of input String, String.split() method treats beginning of the String as the first element to store in result array. With that replaceFirst() method, you get rid of all non-digit characters present at the very beginning of input String.

.split("\\D+") – split the result from the previous operation on one or more non-digit characters.

Note: If you would use just String[] splitted = s.split("\\D+"); (without replaceFirst() part, output would look like this: [, 1, 2, 45, 87], what was not your intention.

solved Java – Convert a string of multiple characters to just a string of numbers