How can I get inside parentheses value in a string?

前端 未结 10 725
半阙折子戏
半阙折子戏 2020-12-23 13:35

How can I get inside parentheses value in a string?

String str= "United Arab Emirates Dirham (AED)";

I need only AED text.

相关标签:
10条回答
  • 2020-12-23 14:26

    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.

    0 讨论(0)
  • 2020-12-23 14:32

    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;
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-23 14:36

    This works...

    String str = "United Arab Emirates Dirham (AED)";
    String answer = str.substring(str.indexOf("(")+1,str.indexOf(")"));
    
    0 讨论(0)
  • 2020-12-23 14:37

    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));
    }
    
    0 讨论(0)
提交回复
热议问题