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
}
}
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.
Groovy supports integer and floating point numbers. An integer is a value that does not include a fraction.
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 ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With