加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

比较groovy中的版本字符串

发布时间:2020-12-14 16:34:15 所属栏目:大数据 来源:网络整理
导读:嘿我已经创建了一个Groovy脚本,它将提取某些文件夹的版本号.然后我想比较版本号并选择最高版本. 我让我的脚本通过dir文件夹运行,然后我得到这种格式的版本:02.2.02.01 所以我可以得到这样的东西: 02.2.02.01 02.2.02.02 02.2.03.01 我没有它们作为列表,但
嘿我已经创建了一个Groovy脚本,它将提取某些文件夹的版本号.然后我想比较版本号并选择最高版本.

我让我的脚本通过dir文件夹运行,然后我得到这种格式的版本:02.2.02.01

所以我可以得到这样的东西:

> 02.2.02.01
> 02.2.02.02
> 02.2.03.01

我没有它们作为列表,但像这样:

baseDir.listFiles().each { file -> 
  def string = file.getName().substring(5,15)
  // do stuff
}

我也测试过Groovy可以将它们与>进行比较.运算符,它可以!但现在我需要选择版本最高的那个

解决方法

这似乎有效

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

这是一组不充分的测试.你应该再添加一些.

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控制台中运行此代码和测试以验证它是否有效

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读