How can I get inside parentheses value in a string?

前端 未结 10 723
半阙折子戏
半阙折子戏 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.

提交回复
热议问题