Extract numeric data from string in groovy

Putting this here for people that also need this.

Instead of creating new question, all I needed was one number from a string.

I did this with regex.

def extractInt( String input ) {
  return input.replaceAll("[^0-9]", "")
}

Where input could be this.may.have.number4.com and return 4

I was receiving error from above answer (probably due to my Jenkins version) - For some reason I get this: java.lang.UnsupportedOperationException: spread not yet supported in input.findAll(\d+)*.toInteger() ---- And it says on Jenkins its resolved.

Hope this helps.


After adding the method below ,numbersFilter,via metaClass , you can call it as following :

assert " i am a positive number 14".numbersFilter() == [ 14 ]
assert " we 12 are 20.3propaged 10.7".numbersFilter() == [ 12,20.3,10.7 ]
assert " we 12 a20.3p 10.7 ,but you can select one".numbersFilter(0) == 12
assert " we 12 a 20.3 pr 10.7 ,select one by index".numbersFilter(1) == 20.3

Add this code As BootStrap

String.metaClass.numbersFilter={index=-1->
            def tmp=[];
            tmp=delegate.findAll( /-?\d+\.\d*|-?\d*\.\d+|-?\d+/ )*.toDouble()
            if(index<=-1){
                return tmp;
            }else{
                if(tmp.size()>index){
                    return tmp[index];
                }else{
                   return tmp.last();
                }
            }

}

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 ]

Tags:

String

Groovy