简体   繁体   中英

Parse() Version Number with a groovy script?

First time posting here. I would like to ask if there's a way to parse a version number using a groovy script.

I extract from Ariba a payload, the issue comes with a specific field called ItemNumber. At first it was working, but this month I started to retrieve a version instead of a float.

This is the part of the script that needs to be changed, but I can't find a way to do it.

if (ItemNumber?.trim()){
    list.ItemNumber = Double.parseDouble(ItemNumber.toString());
}

Any help is greatly appreciated,

Thank you, Kostas

To parse a version number, you will need to tokenize the string. You should create a Version class to hold the version information. This can help when sorting a list of versions. After tokenizing, you can call the Version constructor, and pass the tokens as integers.

Once you have a Version object, you can access fields like major , minor , and patch .

class Version {
   int major
   Integer minor, patch
   @Override String toString() {
       return [major, minor, patch].findAll().join('.')
   }
}

def parseVersion(String versionString) {
    if (!versionString) return null
    int[] tokens = versionString.split(/\./).collect { it as int }
    return new Version(
        major: tokens[0],
        minor: tokens.length > 1 ? tokens[1] : null,
        patch: tokens.length > 2 ? tokens[2] : null,
    )
}

class Payload {
   String ItemNumber
}

Payload payload = new Payload(ItemNumber: "2.4")
Version version = parseVersion(payload.ItemNumber?.trim())
printf("Major version : %d%n", version.major)
printf("Minor version : %s%n", version.minor ?: "<UNSET>")
printf("Patch version : %s%n", version.patch ?: "<UNSET>")
printf("Full version  : %s%n", version)

In later versions of Groovy, you can call the Versions constructor like this:

new Version(major: tokens[0], minor: tokens?[1], patch: tokens?[2])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM