How to convert a Java string against a pattern regex?

Nono :

I want to convert a component version (for example 2.6.0) to this form G02R06C00. I think it's possible with regex and pattern with Java but I don't found how. I have seen examples to match a string against a pattern (in this case the regex would be G\d\dR\d\dC\d\d I guess), but I don't find how to convert a string to other string with a pattern. Thanks in advance.

What I have done is:

String gorocoVersion = version.replaceAll("(\\d*)\\.(\\d*)\\.(\\d*)", "G$1R$2C$3");

that produces G2R6C0, it's missing yet to add 0 to match 2 digits. So, I have to split input string before and I can't anymore use replaceAll, that's why I was looking for more clever option that automatically add 0 before simple digit too according to the output pattern G\d\dR\d\dC\d\d, like we can find in word or excel

Something that works with snapshot version but it's very ugly :

/**
 * @return version in G00R00C00(-SNAPSHOT) format.
 */
private String formatVersion() {
    String gorocoVersion = "";
    if (StringUtils.isNotBlank(version)) {
        String[] versionTab = version.split("\\.");
        String partG = String.format("%02d", Integer.parseInt(versionTab[0]));
        String partR = String.format("%02d", Integer.parseInt(versionTab[1]));

        String partC = versionTab[2];
        String snapshotSuffix = "-SNAPSHOT";
        if (partC.endsWith(snapshotSuffix)) {
            partC = String.format("%02d",
                    Integer.parseInt(partC.substring(0, partC.indexOf('-')))) + snapshotSuffix;
        } else {
            partC = String.format("%02d", Integer.parseInt(partC));
        }

        gorocoVersion = "G" + partG + "R" + partR + "C" + partC;
    }
    return gorocoVersion;
}
Ilya Lysenko :

Try this method:

private static String formatVersion(String version) {
    Pattern pattern = Pattern.compile("^(\\d+)\\.(\\d+)\\.(\\d+)(-SNAPSHOT)*$");
    Matcher matcher = pattern.matcher(version);
    if (matcher.find()) {
        return String.format("G%02dR%02dC%02d", Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2)), Integer.parseInt(matcher.group(3)));
    } else {
        throw new IllegalArgumentException("Unsupported version format");
    }
}

Output for the version param value 2.6.0:

G02R06C00

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=384905&siteId=1