1

I want to extract Numbers from a string, example message is like this

Hello Your Account NO 295093491783 is been deducted by 17820.if you did not receive the Ack call 9897123456.

Right now i am using Google's Guava Like this

String temp = CharMatcher.JAVA_DIGIT.retainFrom(message);

for which I am getting the result like 295093491783178209897123456 and my desired format is

String[] a = {"295093491783", "17820", "9897123456"}

Any help would be appreciated. I Wanted to do this using the guava library.

Note:-

  1. I don't want to use regex because CharMatcher is faster than regex.

  2. My current solution is almost running at 6000 tps (Transactions Per Second).

Naman
  • 27,789
  • 26
  • 218
  • 353
Prakhar Nigam
  • 678
  • 3
  • 15

1 Answers1

2

This may work for you:

static String[] getNumbers(String from) {
    List<String> numbers = new ArrayList<>();
    StringBuilder number = new StringBuilder();
    for (int i = 0; i < from.length(); i++) {
        char c = from.charAt(i);
        if (Character.isDigit(c)) {
            number.append(c);
        } else if (number.length() > 0){
            numbers.add(number.toString());
            number.setLength(0);
        }
    }
    if (number.length() > 0) {
        numbers.add(number.toString());
    }
    return numbers.toArray(new String[numbers.size()]);
}

But have you actually benchmarked the regex solution?

xehpuk
  • 7,814
  • 3
  • 30
  • 54
  • No-till now i haven't benchmarked the RegEx solution. – Prakhar Nigam Mar 17 '18 at 17:55
  • @PrakharNigam let me know the results, seems like micro-optimizaton to not use regex since your input is so tiny. – Karol Dowbecki Mar 17 '18 at 18:09
  • 1
    @KarolDowbecki actually this is a single fragment of a message. my actual message can be of multi-part with a minimum of as such 3 fragments and maximum up to 256 fragments. i am comparing both the solutions i will share the scores for both soon – Prakhar Nigam Mar 17 '18 at 18:17