How can I get inside parentheses value in a string?
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.
Compiles and prints "AED". Even works for multiple parenthesis:
import java.util.regex.*;
public class Main
{
public static void main (String[] args)
{
String example = "United Arab Emirates Dirham (AED)";
Matcher m = Pattern.compile("\\(([^)]+)\\)").matcher(example);
while(m.find()) {
System.out.println(m.group(1));
}
}
}
The regex means:
\\(
: character(
(
: start match group[
: one of these characters^
: not the following character)
: with the previous^
, this means "every character except)
"+
: one of more of the stuff from the[]
set)
: stop match group\\)
: literal closing paranthesis
This works...
String str = "United Arab Emirates Dirham (AED)";
String answer = str.substring(str.indexOf("(")+1,str.indexOf(")"));
i can't get idea how to split inside parentheses. Would you help highly appreciated
When you split you are using a reg-ex, therefore some chars are forbidden.
I think what you are looking for is
str = str.split("[\\(\\)]")[1];
This would split by parenthesis. It translates into split by (
or )
. you use the double \\
to escape the paranthese which is a reserved character for regular expressions.
If you wanted to split by a .
you would have to use split("\\.")
to escape the dot as well.