Skip to content

Instantly share code, notes, and snippets.

@Chunlin-Li
Created June 17, 2015 10:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Chunlin-Li/27059eb766df6b487090 to your computer and use it in GitHub Desktop.
Save Chunlin-Li/27059eb766df6b487090 to your computer and use it in GitHub Desktop.
版本字符串的比较
/**
* 比较两个版本。 0 :两个版本相等; 1 : version1 > version2; -1 : version1 < version2
* 仅适用于由数字和 "." 符号构成的版本号字符串。 对应正则规则 \d+(\.\d+)+
* 如果 version1 和 version 2 均为 empty 返回0 , 否则 empty 恒小于任意字符串。
*/
private static int compareVersionString(String version1, String version2) {
if(StringUtils.isEmpty(version1)) {
if(StringUtils.isEmpty(version2)){
return 0;
} else {
return -1;
}
} else if(StringUtils.isEmpty(version2)) {
return 1;
}
if(!version1.matches("\\d+(\\.\\d+)+") || !version2.matches("\\d+(\\.\\d+)+")){
throw new RuntimeException("version format error! version1 : " + version1 + " version2:" + version2);
}
String[] ver1Array = version1.split("\\.");
String[] ver2Array = version2.split("\\.");
for(int i = 0; i < Math.min(ver1Array.length, ver2Array.length); i++ ) {
int n1 = Integer.parseInt(ver1Array[i]);
int n2 = Integer.parseInt(ver2Array[i]);
if(n1 != n2) {
return n1 > n2 ? 1 : -1;
}
}
if (ver1Array.length > ver2Array.length) {
return 1;
} else if (ver1Array.length < ver2Array.length) {
return -1;
} else {
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment