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

标签 string 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 ]

关于string - 从groovy中的字符串中提取数字数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15572481/

相关文章:

Grails 和 hsqldb

grails - 将 src/groovy 类中的值设置为域类属性

java - 玩!框架 ENUM 和 Groovy 问题

javascript - 将数据从 Native Activity 传递到 WebView

javascript - 替换符合条件的括号

c# - 如何评估此字符串串联?

Jenkins 工作流程 : Parallelize step based on tool output

c++ - 使用 const char* 作为 map/unordered_map 的键

R:如何使用函数参数作为变量名的一部分

java - 漏洞!阶段 'semantic analysis' 中的异常