How to Extract String Between Parentheses in Java


Let’s see how we can extract a string between parentheses in Java with and without regular expressions.

1. Using String::matches

The String.matches() method can be used to check if a string matches a regular expression.

String extract(String input) {
  return input.replaceAll(".*\\(([^)]+)\\).*", "$1")
}

2. Using Matcher::find

The Matcher.find() method can be used to find a substring that matches a regular expression.

String extract(String input) {
  Matcher matcher = Pattern.compile("\\(([^)]+)\\)").matcher(input);
  if (matcher.find()) {
    return matcher.group(1);
  }
  return input;
}

3. Using String::split

The String.split() method can be used to split a string into an array of substrings based on a regular expression.

String extract(String input) {
  return input.split("\\(([^)]+)\\)")[1]
}

4. Using String::substring

The String.substring() method can be used to split a string into an array of substrings based on index.

String extract(String input) {
  return input.substring(input.indexOf("(") + 1, input.indexOf(")"));
}