-2

I have the following String input.

String s = "I have 5000 bananas";

I am extracting the numeric value using a regex String regex = "\\b\\d+\\b". This Regex is good in the sense that it would exclude any numericalAlpha mix words like a4 bc3.

The issue happens when the user will input Strings like

String s1 = "I have 2 345 bananas";
String s2 = "I have 2,345 bananas";
String s3 = "I have #2345 bananas";
String s4 = "I have 5654 6 bananas";

My program should output an empty string in the above cases as none are valid numbers in the input String.

fuentesj
  • 154
  • 7
Asif
  • 49
  • 1
  • 9
  • That didn't work. but thanks for your help – Asif Apr 05 '20 at 22:16
  • Try experimenting with [regex101](https://regex101.com/?regex=%5Ba-z%5D%20(%5Cd%2B)%20%5Ba-z%5D&testString=I%20have%205000%20bananas%0D%0AI%20have%202%20345%20bananas%0D%0AI%20have%202,345%20bananas%0D%0AI%20have%20%232345%20bananas%0D%0AI%20have%205654%206%20bananas), that may help. – zakinster Apr 06 '20 at 08:23

1 Answers1

0

You want to use a capturing group and the String method replaceAll.

...

String[] strs = new String[] {
    "I have 5000 bananas",
    "I have 2 345 bananas",
    "I have 2,345 bananas",
    "I have #2345 bananas",
    "I have 5654 6 bananas"
};

for (String s : strs) {
    if (s.matches("(\\d+)( \\D+)")) {
        System.out.println(s.replaceAll("(\\d+)( \\D+)", "$1"));
    }
    else if (s.matches("(\\D+ )(\\d+)")) {
        System.out.println(s.replaceAll("(\\D+ )(\\d+)", "$2"));
    }
    else if (s.matches("(\\D+ )(\\d+)( \\D+)")) {
        System.out.println(s.replaceAll("(\\D+ )(\\d+)( \\D+)", "$2"));
    }
    else {
        // Just for demonstration on "displaying" or
        // if you need to return or assign an empty string
        System.out.println("");
    }
}

...

Running that for your provided test cases will yield: (I am using the string "No match" instead of an empty string just to demonstrate)

5000
No match
No match
No match
No match
fuentesj
  • 154
  • 7