Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract numeric data from string in groovy

Tags:

string

groovy

I am given a string that can include both text and numeric data:

Examples:

"100 pounds" "I think 173 lbs" "73 lbs."

I am looking for a clean way to extract only the numeric data from these strings.

Here is what I'm currently doing to strip the response:

def stripResponse(String response) {
    if(response) {
        def toRemove = ["lbs.", "lbs", "pounds.", "pounds", " "]
        def toMod = response
        for(remove in toRemove) {
            toMod = toMod?.replaceAll(remove, "")
        }
        return toMod
    }
}
like image 927
Joel Miller Avatar asked Mar 22 '13 14:03

Joel Miller


People also ask

How do I strip a string in Groovy?

Groovy has added the minus() method to the String class. And because the minus() method is used by the - operator we can remove parts of a String with this operator. The argument can be a String or a regular expression Pattern. The first occurrence of the String or Pattern is then removed from the original String.

Is integer in Groovy?

Groovy supports integer and floating point numbers. An integer is a value that does not include a fraction.


1 Answers

You could use findAll then convert the results into Integers:

def extractInts( String input ) {
  input.findAll( /\d+/ )*.toInteger()
}

assert extractInts( "100 pounds is 23"  ) == [ 100, 23 ]
assert extractInts( "I think 173 lbs"   ) == [ 173 ]
assert extractInts( "73 lbs."           ) == [ 73 ]
assert extractInts( "No numbers here"   ) == []
assert extractInts( "23.5 only ints"    ) == [ 23, 5 ]
assert extractInts( "positive only -13" ) == [ 13 ]

If you need decimals and negative numbers, you might use a more complex regex:

def extractInts( String input ) {
  input.findAll( /-?\d+\.\d*|-?\d*\.\d+|-?\d+/ )*.toDouble()
}

assert extractInts( "100 pounds is 23"   ) == [ 100, 23 ]
assert extractInts( "I think 173 lbs"    ) == [ 173 ]
assert extractInts( "73 lbs."            ) == [ 73 ]
assert extractInts( "No numbers here"    ) == []
assert extractInts( "23.5 handles float" ) == [ 23.5 ]
assert extractInts( "and negatives -13"  ) == [ -13 ]
like image 173
tim_yates Avatar answered Sep 16 '22 11:09

tim_yates