0

I need to extract ALL the numbers from a string. I am going with this so that I can convert the numbers in scientific notation to decimal form, keeping the rest of the string intact.

Example: "the distance is 4.62664581051E9" becomes "the distance is 4626645810.51"

public static void main (String[] args) throws java.lang.Exception
{
        NumberFormat fm1 = new DecimalFormat(",##0.00##");
        String str = "NetMV4.62664581051E9";
        StringBuilder parameterBuilder = new StringBuilder();
        Scanner scanner = new Scanner(str);

        while (scanner.hasNext()) {
            if (scanner.hasNextDouble() && !scanner.hasNextInt()) {
                parameterBuilder.append(fm1.format(scanner.nextDouble()));
            } else {
                parameterBuilder.append(scanner.next() + " ");
            }
        }       
        scanner.close();
        System.out.println(parameterBuilder.toString());
}

Up till now I was using Scanner class to extract the numbers. It works fine but fails for cases such as "the distance=4.62664581051E9" (no spaces)

I could create a custom parser and parse through the string but was looking for better cases.

Thanks

Ankit Jain
  • 315
  • 3
  • 18
  • Don't match on delimiters, use a positive match on the number itself. So, don't use Scanner because it's the wrong tool. Use `Pattern.compile(...).matcher(input)`, then a loop on `matcher.find()`. – Marko Topolnik Mar 12 '15 at 07:51

1 Answers1

0

How's about using regular expression? If it would be OK, using:

[-+]?[0-9]*.?[0-9]+([eE][-+]?[0-9]+)?

This is the answer from here

Testing: https://regex101.com/r/bK8iH9/1

Community
  • 1
  • 1
Kingcesc
  • 84
  • 1
  • 6