How can I get inside parentheses value in a string?

前端 未结 10 740
半阙折子戏
半阙折子戏 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:17

    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

提交回复
热议问题