When it comes to parsing a version number, the first step is to tokenize the string. It's recommended to create a custom class called Version
to store all the version details. This makes it easier to manage and sort a collection of versions. Once the string is tokenized, you can instantiate a new Version
object by passing the tokens as integer values.
With a Version
object in hand, you can easily access fields such as 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 releases of Groovy, the Version
constructor can be invoked in a simplified manner like this:
new Version(major: tokens[0], minor: tokens?[1], patch: tokens?[2])