String 在groovy中从字符串中提取数字数据

String 在groovy中从字符串中提取数字数据,string,groovy,String,Groovy,我收到一个字符串,该字符串可以包含文本和数字数据: 示例: “100英镑” “我想173磅” “73磅。” 我正在寻找一种只从这些字符串中提取数字数据的干净方法 以下是我目前正在做的剥离响应的操作: def stripResponse(String response) { if(response) { def toRemove = ["lbs.", "lbs", "pounds.", "pounds", " "] def toMod = response

我收到一个字符串,该字符串可以包含文本和数字数据:

示例:

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

添加下面的方法后,
numbersFilter
,通过元类,您可以如下调用它:

assert " i am a positive number 14".numbersFilter() == [ 14 ]
assert " we 12 are 20.3propaged 10.7".numbersFilter() == [ 12,20.3,10.7 ]
assert " we 12 a20.3p 10.7 ,but you can select one".numbersFilter(0) == 12
assert " we 12 a 20.3 pr 10.7 ,select one by index".numbersFilter(1) == 20.3
将此代码添加为引导

String.metaClass.numbersFilter={index=-1->
            def tmp=[];
            tmp=delegate.findAll( /-?\d+\.\d*|-?\d*\.\d+|-?\d+/ )*.toDouble()
            if(index<=-1){
                return tmp;
            }else{
                if(tmp.size()>index){
                    return tmp[index];
                }else{
                   return tmp.last();
                }
            }

}
String.metaClass.numbersFilter={index=-1->
def tmp=[];
tmp=delegate.findAll(/-?\d+\.\d*.\d*.\d+.\d+.\d+.\d+/)*.toDouble()
if(索引索引){
返回tmp[索引];
}否则{
返回tmp.last();
}
}
}

把这个放在这里是为了那些同样需要它的人

我所需要的不是创建新问题,而是字符串中的一个数字

我是用regex做的

def extractInt( String input ) {
  return input.replaceAll("[^0-9]", "")
}
其中输入可以是
this.may.have.number4.com
并返回
4


我从上面的回答中收到了错误(可能是由于我的Jenkins版本)-出于某种原因,我得到了以下信息:
java.lang.UnsupportedOperationException:spread在input.findAll(\d+)*.toInteger()
----中不受支持,并且它在其上显示了已解决的问题


希望这能有所帮助。

在逐行解析String.contains和String.replaceAll(用空格替换所有非数字字符序列)时 然后是String.split() 组合很有用,如下所示:

if (line.contains("RESULT:")) {
    l = line.replaceAll("[^0-9][^0-9]*"," ")
    a = l.split()
    pCount1 = Integer.parseInt(a[0])
    pCount2 = Integer.parseInt(a[1])
}
String.findAll解决方案更好! 等价物:

if (line.contains("RESULT:")) {
    a = line.findAll( /\d+/ )*.toInteger()
    pCount1 = a[0]
    pCount2 = a[1]
}
因为input.findAll(/\d+/)*.toInteger()不能与Jenkins一起使用。你可以用这个代替

def packageVersion = "The package number is 9.2.5847.1275"
def nextversion=packageVersion.findAll( /\d+/ ).collect{ "$it".toInteger() }
nextversion.add(nextversion.pop()+1)
nextversion = nextversion.join('.')
Result: 9.2.5847.1276

另一个替代解决方案,没有RegEx。它将字符串解析为标记,并将其转换为数字或空值列表。删除空值,最后只考虑第一个条目(根据需要)


我最终根据上面的建议实现的解决方案,我只想获取第一个数字(如果有多个,我将使响应无效)。谢谢@tim_yates<代码>def extractNumericData(字符串响应){if(响应){def numberList=response.findAll(/[0-9]+[0-9]*.[0-9]+[0-9]+/)if(numberList.size()==1){返回numberList.get(0)作为BigDecimal}否则{return return 1}出于某种原因,我得到了以下信息:
java.lang.UnsupportedOperationException:spread在input.findAll(\d+*.toInteger())中还不受支持--它在resolved.Upvoted上表示,因为虽然它没有回答确切的问题,但如果您想解析多个整数,它提供了一个很好的简单子casereplaceAll和replace with space。e、 g.input.replaceAll(“[^0-9][^0-9]*”,“”)
def extractNumericData(String response) {
    response.split(' ')
        .collect { it.isFloat() ? Float.parseFloat(it) : null }
        .findAll { it }
        .first()
}

assert 100 == extractNumericData("100 pounds")
assert 173 == extractNumericData("I think 173 lbs")
assert 73 == extractNumericData("73 lbs.")