给我一个可以同时包含文本和数字数据的字符串:
例子:
“ 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
然后将结果转换为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 ]
如果你需要小数和负数,则可以使用更复杂的正则表达式:
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 ]
我最终根据上述建议实施了该解决方案,我只想获取第一个数字(如果有多个,我会使响应无效)。谢谢@tim_yates!
def extractNumericData(String response) { if(response) { def numberList = response.findAll( /[0-9]+.[0-9]*|[0-9]*.[0-9]+|[0-9]+/ ) if(numberList.size() == 1) { return numberList.get(0) as BigDecimal } else { return -1 } } }
由于某种原因,我得到了:
java.lang.UnsupportedOperationException: spread not yet supported in input.findAll(\d+)*.toInteger()
。----在詹金斯说它已经解决了。