Skip to content
Advertisement

Pattern to extract text between parenthesis

How to extract string from "(" and ")" using pattern matching or anything. For example if the text is

“Hello (Java)”

Then how to get only "Java"?

Advertisement

Answer

Try this:

String x = "Hello (Java)";
Matcher m = Pattern.compile("\((.*?)\)").matcher(x);
while (m.find()) {
    System.out.println(m.group(1));
}

or

String str = "Hello (Java)";
String answer = str.substring(str.indexOf("(")+1, str.indexOf(")"));
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement