Carvallegro
Carvallegro

Reputation: 1341

Java library to analyze String and extract numbers

I know that the title is quite vague but I'm gonna explain what I'm looking for.
I have to analyze a lot of data from various sources and I'd like to check if a value can be interpreted as a numeric value. I know there are regex and all but, the thing is that I have a lot of number formatted in various way, depending on where they come from :

I'm looking for a library able to analyze those String and return either the numeric value or the corresponding pattern. It would save me a lot of time !

Thank's

Upvotes: 0

Views: 163

Answers (3)

chandra
chandra

Reputation: 41

I consider the below method will meet your needs :

   public Double getNumber( String str ) {
    str = str.replace("'", "").replace(",","").replace(" ","").trim();

    try {
        Double num = Double.parseDouble(str);
        return num;
    } catch( NumberFormatException nfe ) {
        nfe.printStackTrace();
        return 0.0;
    }
}

Upvotes: 1

nafas
nafas

Reputation: 5423

Use a set of regular expression to do that. for example For English numbers you can have something like:

(([0-9]+),[0-9]+){1,}((\.)[0-9]+)?    

This will find numbers like

  • 232,23,34.4
  • 34,3,43

but not :

  • 343
  • 343.343

I hope This helps.

Upvotes: 1

Jamie Cockburn
Jamie Cockburn

Reputation: 7555

Since there is no way to tell is the string "123,456" is a French notation for 123.456 (one-hundred and twenty-three point four, five, six) or the English notation for 123456 (one-hundred and twenty-three thousand, four-hundred and fifty six), there is no reliable way to do what you ask.

Upvotes: 4

Related Questions