groovy if 判断字符串_比较groovy中的版本字符串

Hey I have created a Groovy script that will extract the version numbers of some folder. I would then like to compare the version numbers and select the highest.

I got my script to run through the dir folder and I then get the versions in this format: 02.2.02.01

So I could get something like this:

02.2.02.01

02.2.02.02

02.2.03.01

I don't have them as a list but like this:

baseDir.listFiles().each { file ->

def string = file.getName().substring(5, 15)

// do stuff

}

Also I have tested that Groovy could compare them with the > operator and it can! But now I need to select the one with the highest version

解决方案

This appears to work

String mostRecentVersion(List versions) {

def sorted = versions.sort(false) { a, b ->

List verA = a.tokenize('.')

List verB = b.tokenize('.')

def commonIndices = Math.min(verA.size(), verB.size())

for (int i = 0; i < commonIndices; ++i) {

def numA = verA[i].toInteger()

def numB = verB[i].toInteger()

println "comparing $numA and $numB"

if (numA != numB) {

return numA <=> numB

}

}

// If we got this far then all the common indices are identical, so whichever version is longer must be more recent

verA.size() <=> verB.size()

}

println "sorted versions: $sorted"

sorted[-1]

}

Here is an inadequate set of tests. You should add some more.

assert mostRecentVersion(['02.2.02.01', '02.2.02.02', '02.2.03.01']) == '02.2.03.01'

assert mostRecentVersion(['4', '2']) == '4'

assert mostRecentVersion(['4.1', '4']) == '4.1'

assert mostRecentVersion(['4.1', '5']) == '5'

Run this code and the tests in the Groovy console to verify that it works

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值