Comparing version number strings (major, minor, revision, beta)

前端 未结 3 1184
花落未央
花落未央 2021-01-04 05:58

I have an application that communicates with the firmware of a device. As there are changes to the firmware, it is versioned with the format {major}.{minor}.{revision}

3条回答
  •  暖寄归人
    2021-01-04 06:47

    Here's one suggestion:

    static int[] getVersionNumbers(String ver) {
        Matcher m = Pattern.compile("(\\d+)\\.(\\d+)\\.(\\d+)(beta(\\d*))?")
                           .matcher(ver);
        if (!m.matches())
            throw new IllegalArgumentException("Malformed FW version");
    
        return new int[] { Integer.parseInt(m.group(1)),  // major
                Integer.parseInt(m.group(2)),             // minor
                Integer.parseInt(m.group(3)),             // rev.
                m.group(4) == null ? Integer.MAX_VALUE    // no beta suffix
                        : m.group(5).isEmpty() ? 1        // "beta"
                        : Integer.parseInt(m.group(5))    // "beta3"
        };
    }
    
    static boolean isFirmwareNewer(String testFW, String baseFW) {
    
        int[] testVer = getVersionNumbers(testFW);
        int[] baseVer = getVersionNumbers(baseFW);
    
        for (int i = 0; i < testVer.length; i++)
            if (testVer[i] != baseVer[i])
                return testVer[i] > baseVer[i];
    
        return true;
    }
    

    It uses a little trick and translates the beta-part as follows:

    • "" (no beta suffix) → Beta MAX_INT
    • "beta" → Beta 1 (since it preceeds "beta2")
    • "betaX" → Beta X

    Note that it return true if both versions are identical.

提交回复
热议问题