从groovy中的字符串中提取数字数据

我给了一个可以包含文本和数字数据的字符串:

例子:

“100磅”
“我觉得173磅”
“73磅”

我正在寻找一种干净的方法提取这些字符串中的数字数据.

这是我目前正在做的以剥离回应:

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
    }
}

解决方法

您可以使用findAll然后将结果转换为整数:

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 ]

如果您需要小数和负数,则可能使用更复杂的正则表达式:

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 ]

相关文章

背景:    8月29日,凌晨4点左右,某服务告警,其中一个...
https://support.smartbear.comeadyapi/docs/soapui/steps/g...
有几个选项可用于执行自定义JMeter脚本并扩展基线JMeter功能...
Scala和Java为静态语言,Groovy为动态语言Scala:函数式编程,...
出处:https://www.jianshu.com/p/ce6f8a1f66f4一、一些内部...
在运行groovy的junit方法时,报了这个错误:java.lang.Excep...