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

从groovy中的字符串中提取数字数据,第1张

概述我给了一个可以包含文本和数字数据的字符串: 例子: “100磅” “我觉得173磅” “73磅” 我正在寻找一种干净的方法来提取这些字符串中的数字数据. 这是我目前正在做的以剥离回应: def stripResponse(String response) { if(response) { def toRemove = ["lbs.", "lbs", "pounds.", " 我给了一个可以包含文本和数字数据的字符串:

例子:

“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 ]
总结

以上是内存溢出为你收集整理的从groovy中的字符串中提取数字数据全部内容,希望文章能够帮你解决从groovy中的字符串中提取数字数据所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1234949.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存