konstantin konstantin - 1 month ago 6
Java Question

Return a specific part from a String in java

I want to change a string so that only the numbers in the parenthesis will be kept. An example of the string is

username123(151231).


And the output should be

151231


How can I return only the numbers in the parenthesis?

Answer
String str = "username123(151231)";
String newstr= str.substring(str.indexOf("(")+1,str.indexOf(")"));

From OP's question it is given there is one set of parenthesis. For other cases use regex.

Matcher m = Pattern.compile("\\(([^)]+)\\)").matcher(str);
Comments