-3

I want to get the data from String "Max(percentage(%))" or "Max(percentage)", what i need to get is "percentage(%)" or "percentage" in the brackets. I want to use one regex achieve the goal. Can someone help me? Below is my code:

String str = "Max(percentage)";
Pattern pattern = Pattern.compile("(?<=\\()(.+?)(?=\\))");

String str = "Max(percentage(%))";
Pattern pattern = Pattern.compile("(?<=\\()(.+?)(?<=\\))");

3 Answers3

-1

Maybe you might try the following regex?

 [^\(]*\(([0-9]+)[)%]?\)
lpg
  • 4,897
  • 1
  • 16
  • 16
-1

Following regex can handle one level of nested parenthesis (to match any number of level a recursive regex should be used but it's not supported by java).

Regex

(?<=Max\()[^()]*(?:\([^()]*\)[^()]*)*(?=\))

Java code

String str = "Max(percentage(%))";
Pattern pattern = Pattern.compile("(?<=Max\\()[^()]*(?:\\([^()]*\\)[^()]*)*(?=\\))");
Nahuel Fouilleul
  • 18,726
  • 2
  • 31
  • 36
-1

I would say use "or" operator | to check whether you have a percentage or a percentage plus (%):

    String str1 = "Max(32)";
    String str2 = "Max(32(%))";

    Pattern pattern = Pattern.compile("Max\\((.+|.+\\(%\\))\\)");

    Matcher matcher1 = pattern.matcher(str1);
    if (matcher1.find()) {
        System.out.println("percentage = " + matcher1.group(1));
    }

    Matcher matcher2 = pattern.matcher(str2);
    if (matcher2.find()) {
        System.out.println("percentage(%) = " + matcher2.group(1));
    }
Ivan Ovitx
  • 21
  • 1
  • 6