比较 groovy 中的版本字符串 [英] Compare version strings in groovy
问题描述
嘿,我已经创建了一个 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.
我让我的脚本通过 dir 文件夹运行,然后我以这种格式获取版本:02.2.02.01
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
}
我还测试了 Groovy 可以将它们与 >>
运算符进行比较,并且确实可以!但是现在我需要选择版本最高的那个
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
推荐答案
这似乎有效
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()
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'
在 Groovy 控制台中运行此代码和测试以验证它是否有效
Run this code and the tests in the Groovy console to verify that it works
这篇关于比较 groovy 中的版本字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!