How can I get inside parentheses value in a string?
String str= "United Arab Emirates Dirham (AED)";
I need only AED text.
I know this was asked over 4 years ago, but for anyone with the same/similar question that lands here (as I did), there is something even simpler than using regex:
String result = StringUtils.substringBetween(str, "(", ")");
In your example, result
would be returned as "AED". I would recommend the StringUtils library for various kinds of (relatively simple) string manipulation; it handles things like null inputs automatically, which can be convenient.
Documentation for substringBetween(): https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#substringBetween-java.lang.String-java.lang.String-java.lang.String-
There are two other versions of this function, depending on whether the opening and closing delimiters are the same, and whether the delimiter(s) occur(s) in the target string multiple times.
I can suggest two ways:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args){
System.out.println(getParenthesesContent1("United Arab Emirates Dirham (AED)"));
System.out.println(getParenthesesContent2("United Arab Emirates Dirham (AED)"));
}
public static String getParenthesesContent1(String str){
return str.substring(str.indexOf('(')+1,str.indexOf(')'));
}
public static String getParenthesesContent2(String str){
final Pattern pattern = Pattern.compile("^.*\\((.*)\\).*$");
final Matcher matcher = pattern.matcher(str);
if (matcher.matches()){
return matcher.group(1);
} else {
return null;
}
}
}
This works...
String str = "United Arab Emirates Dirham (AED)";
String answer = str.substring(str.indexOf("(")+1,str.indexOf(")"));
Using regular expression:
String text = "United Arab Emirates Dirham (AED)";
Pattern pattern = Pattern.compile(".* \\(([A-Z]+)\\)");
Matcher matcher = pattern.matcher(text);
if (matcher.matches()) {
System.out.println("found: " + matcher.group(1));
}