是否有比较版本号的标准习语?我不能直接使用String compareTo,因为我还不知道点释放的最大数量是多少。我需要比较版本,并有以下保持正确:
1.0 < 1.1
1.0.1 < 1.1
1.9 < 1.10
是否有比较版本号的标准习语?我不能直接使用String compareTo,因为我还不知道点释放的最大数量是多少。我需要比较版本,并有以下保持正确:
1.0 < 1.1
1.0.1 < 1.1
1.9 < 1.10
当前回答
/**
* written by: Stan Towianski - May 2018
* notes: I make assumption each of 3 version sections a.b.c is not longer then 4 digits: aaaa.bbbb.cccc-MODWORD1(-)modnum2
* 5.10.13-release-1 becomes 0000500100013.501 6.0-snapshot becomes 0000600000000.100
* MODWORD1 = -xyz/NotMatching, -SNAPSHOT, -ALPHA, -BETA, -RC, -RELEASE/nothing return: .0, .1, .2, .3, .4, .5
* modnum2 = up to 2 digit/chars second version
* */
public class VersionCk {
private static boolean isVersionHigher( String baseVersion, String testVersion )
{
System.out.println( "versionToComparable( baseVersion ) =" + versionToComparable( baseVersion ) );
System.out.println( "versionToComparable( testVersion ) =" + versionToComparable( testVersion ) + " is this higher ?" );
return versionToComparable( testVersion ).compareTo( versionToComparable( baseVersion ) ) > 0;
}
//---- not worrying about += for something so small
private static String versionToComparable( String version )
{
// System.out.println("version - " + version);
String versionNum = version;
int at = version.indexOf( '-' );
if ( at >= 0 )
versionNum = version.substring( 0, at );
String[] numAr = versionNum.split( "\\." );
String versionFormatted = "0";
for ( String tmp : numAr )
{
versionFormatted += String.format( "%4s", tmp ).replace(' ', '0');
}
while ( versionFormatted.length() < 12 ) // pad out to aaaa.bbbb.cccc
{
versionFormatted += "0000";
}
// System.out.println( "converted min version =" + versionFormatted + "= : " + versionNum );
return versionFormatted + getVersionModifier( version, at );
}
//---- use order low to high: -xyz, -SNAPSHOT, -ALPHA, -BETA, -RC, -RELEASE/nothing returns: 0, 1, 2, 3, 4, 5
private static String getVersionModifier( String version, int at )
{
// System.out.println("version - " + version );
String[] wordModsAr = { "-SNAPSHOT", "-ALPHA", "-BETA", "-RC", "-RELEASE" };
if ( at < 0 )
return "." + wordModsAr.length + "00"; // make nothing = RELEASE level
int i = 1;
for ( String word : wordModsAr )
{
if ( ( at = version.toUpperCase().indexOf( word ) ) > 0 )
return "." + i + getSecondVersionModifier( version.substring( at + word.length() ) );
i++;
}
return ".000";
}
//---- add 2 chars for any number after first modifier. -rc2 or -rc-2 returns 02
private static String getSecondVersionModifier( String version )
{
System.out.println( "second modifier =" + version + "=" );
Matcher m = Pattern.compile("(.*?)(\\d+).*").matcher( version );
// if ( m.matches() )
// System.out.println( "match ? =" + m.matches() + "= m.group(1) =" + m.group(1) + "= m.group(2) =" + m.group(2) + "= m.group(3) =" + (m.groupCount() >= 3 ? m.group(3) : "x") );
// else
// System.out.println( "No match" );
return m.matches() ? String.format( "%2s", m.group(2) ).replace(' ', '0') : "00";
}
public static void main(String[] args)
{
checkVersion( "3.10.0", "3.4.0");
checkVersion( "5.4.2", "5.4.1");
checkVersion( "5.4.4", "5.4.5");
checkVersion( "5.4.9", "5.4.12");
checkVersion( "5.9.222", "5.10.12");
checkVersion( "5.10.12", "5.10.12");
checkVersion( "5.10.13", "5.10.14");
checkVersion( "6.7.0", "6.8");
checkVersion( "6.7", "2.7.0");
checkVersion( "6", "6.3.1");
checkVersion( "4", "4.0.0");
checkVersion( "6.3.0", "6");
checkVersion( "5.10.12-Alpha", "5.10.12-beTA");
checkVersion( "5.10.13-release", "5.10.14-beta");
checkVersion( "6.7.0", "6.8-snapshot");
checkVersion( "6.7.1", "6.7.0-release");
checkVersion( "6-snapshot", "6.0.0-beta");
checkVersion( "6.0-snapshot", "6.0.0-whatthe");
checkVersion( "5.10.12-Alpha-1", "5.10.12-alpha-2");
checkVersion( "5.10.13-release-1", "5.10.13-release2");
checkVersion( "10-rc42", "10.0.0-rc53");
}
private static void checkVersion(String baseVersion, String testVersion)
{
System.out.println( "baseVersion - " + baseVersion );
System.out.println( "testVersion - " + testVersion );
System.out.println( "isVersionHigher = " + isVersionHigher( baseVersion, testVersion ) );
System.out.println( "---------------");
}
}
一些输出:
---------------
baseVersion - 6.7
testVersion - 2.7.0
versionToComparable( baseVersion ) =0000600070000.500
versionToComparable( testVersion ) =0000200070000.500 is this higher ?
isVersionHigher = false
---------------
baseVersion - 6
testVersion - 6.3.1
versionToComparable( baseVersion ) =0000600000000.500
versionToComparable( testVersion ) =0000600030001.500 is this higher ?
isVersionHigher = true
---------------
baseVersion - 4
testVersion - 4.0.0
versionToComparable( baseVersion ) =0000400000000.500
versionToComparable( testVersion ) =0000400000000.500 is this higher ?
isVersionHigher = false
---------------
baseVersion - 6.3.0
testVersion - 6
versionToComparable( baseVersion ) =0000600030000.500
versionToComparable( testVersion ) =0000600000000.500 is this higher ?
isVersionHigher = false
---------------
baseVersion - 5.10.12-Alpha
testVersion - 5.10.12-beTA
second modifier ==
versionToComparable( baseVersion ) =0000500100012.200
second modifier ==
versionToComparable( testVersion ) =0000500100012.300 is this higher ?
second modifier ==
second modifier ==
isVersionHigher = true
---------------
baseVersion - 5.10.13-release
testVersion - 5.10.14-beta
second modifier ==
versionToComparable( baseVersion ) =0000500100013.500
second modifier ==
versionToComparable( testVersion ) =0000500100014.300 is this higher ?
second modifier ==
second modifier ==
isVersionHigher = true
---------------
baseVersion - 6.7.0
testVersion - 6.8-snapshot
versionToComparable( baseVersion ) =0000600070000.500
second modifier ==
versionToComparable( testVersion ) =0000600080000.100 is this higher ?
second modifier ==
isVersionHigher = true
---------------
baseVersion - 6.7.1
testVersion - 6.7.0-release
versionToComparable( baseVersion ) =0000600070001.500
second modifier ==
versionToComparable( testVersion ) =0000600070000.500 is this higher ?
second modifier ==
isVersionHigher = false
---------------
baseVersion - 6-snapshot
testVersion - 6.0.0-beta
second modifier ==
versionToComparable( baseVersion ) =0000600000000.100
second modifier ==
versionToComparable( testVersion ) =0000600000000.300 is this higher ?
second modifier ==
second modifier ==
isVersionHigher = true
---------------
baseVersion - 6.0-snapshot
testVersion - 6.0.0-whatthe
second modifier ==
versionToComparable( baseVersion ) =0000600000000.100
versionToComparable( testVersion ) =0000600000000.000 is this higher ?
second modifier ==
isVersionHigher = false
---------------
baseVersion - 5.10.12-Alpha-1
testVersion - 5.10.12-alpha-2
second modifier =-1=
versionToComparable( baseVersion ) =0000500100012.201
second modifier =-2=
versionToComparable( testVersion ) =0000500100012.202 is this higher ?
second modifier =-2=
second modifier =-1=
isVersionHigher = true
---------------
baseVersion - 5.10.13-release-1
testVersion - 5.10.13-release2
second modifier =-1=
versionToComparable( baseVersion ) =0000500100013.501
second modifier =2=
versionToComparable( testVersion ) =0000500100013.502 is this higher ?
second modifier =2=
second modifier =-1=
isVersionHigher = true
---------------
baseVersion - 10-rc42
testVersion - 10.0.0-rc53
second modifier =42=
versionToComparable( baseVersion ) =0001000000000.442
second modifier =53=
versionToComparable( testVersion ) =0001000000000.453 is this higher ?
second modifier =53=
second modifier =42=
isVersionHigher = true
---------------
其他回答
对于要显示基于版本号的强制更新警报的人,我有以下想法。这可能用于比较Android当前应用版本和firebase远程配置版本之间的版本。这并不是问题的确切答案,但这肯定会对某人有所帮助。
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
public class Main
{
static String firebaseVersion = "2.1.3"; // or 2.1
static String appVersion = "2.1.4";
static List<String> firebaseVersionArray;
static List<String> appVersionArray;
static boolean isNeedToShowAlert = false;
public static void main (String[]args)
{
System.out.println ("Hello World");
firebaseVersionArray = new ArrayList<String>(Arrays.asList(firebaseVersion.split ("\\.")));
appVersionArray = new ArrayList<String>(Arrays.asList(appVersion.split ("\\.")));
if(appVersionArray.size() < firebaseVersionArray.size()) {
appVersionArray.add("0");
}
if(firebaseVersionArray.size() < appVersionArray.size()) {
firebaseVersionArray.add("0");
}
isNeedToShowAlert = needToShowAlert(); //Returns false
System.out.println (isNeedToShowAlert);
}
static boolean needToShowAlert() {
boolean result = false;
for(int i = 0 ; i < appVersionArray.size() ; i++) {
if (Integer.parseInt(appVersionArray.get(i)) == Integer.parseInt(firebaseVersionArray.get(i))) {
continue;
} else if (Integer.parseInt(appVersionArray.get(i)) > Integer.parseInt(firebaseVersionArray.get(i))){
result = false;
break;
} else if (Integer.parseInt(appVersionArray.get(i)) < Integer.parseInt(firebaseVersionArray.get(i))) {
result = true;
break;
}
}
return result;
}
}
您可以通过复制粘贴来运行此代码 https://www.onlinegdb.com/online_java_compiler
此代码尝试解决这种类型的比较版本。
大多数版本说明符,如>= 1.0,都是不言自明的。的 说明符~>具有特殊含义,最好通过示例来说明。~> 2.0.3是 与>= 2.0.3和< 2.1相同。~> 2.1与>= 2.1相同,且< 3.0.
public static boolean apply(String cmpDeviceVersion, String reqDeviceVersion)
{
Boolean equal = !cmpDeviceVersion.contains(">") && !cmpDeviceVersion.contains(">=") &&
!cmpDeviceVersion.contains("<") && !cmpDeviceVersion.contains("<=") &&
!cmpDeviceVersion.contains("~>");
Boolean between = cmpDeviceVersion.contains("~>");
Boolean higher = cmpDeviceVersion.contains(">") && !cmpDeviceVersion.contains(">=") && !cmpDeviceVersion.contains("~>");
Boolean higherOrEqual = cmpDeviceVersion.contains(">=");
Boolean less = cmpDeviceVersion.contains("<") && !cmpDeviceVersion.contains("<=");
Boolean lessOrEqual = cmpDeviceVersion.contains("<=");
cmpDeviceVersion = cmpDeviceVersion.replaceAll("[<>=~]", "");
cmpDeviceVersion = cmpDeviceVersion.trim();
String[] version = cmpDeviceVersion.split("\\.");
String[] reqVersion = reqDeviceVersion.split("\\.");
if(equal)
{
return isEqual(version, reqVersion);
}
else if(between)
{
return isBetween(version, reqVersion);
}
else if(higher)
{
return isHigher(version, reqVersion);
}
else if(higherOrEqual)
{
return isEqual(version, reqVersion) || isHigher(version, reqVersion);
}
else if(less)
{
return isLess(version, reqVersion);
}
else if(lessOrEqual)
{
return isEqual(version, reqVersion) || isLess(version, reqVersion);
}
return false;
}
private static boolean isEqual(String[] version, String[] reqVersion)
{
String strVersion = StringUtils.join(version);
String strReqVersion = StringUtils.join(reqVersion);
if(version.length > reqVersion.length)
{
Integer diff = version.length - reqVersion.length;
strReqVersion += StringUtils.repeat(".0", diff);
}
else if(reqVersion.length > version.length)
{
Integer diff = reqVersion.length - version.length;
strVersion += StringUtils.repeat(".0", diff);
}
return strVersion.equals(strReqVersion);
}
private static boolean isHigher(String[] version, String[] reqVersion)
{
String strVersion = StringUtils.join(version);
String strReqVersion = StringUtils.join(reqVersion);
if(version.length > reqVersion.length)
{
Integer diff = version.length - reqVersion.length;
strReqVersion += StringUtils.repeat(".0", diff);
}
else if(reqVersion.length > version.length)
{
Integer diff = reqVersion.length - version.length;
strVersion += StringUtils.repeat(".0", diff);
}
return strReqVersion.compareTo(strVersion) > 0;
}
private static boolean isLess(String[] version, String[] reqVersion)
{
String strVersion = StringUtils.join(version);
String strReqVersion = StringUtils.join(reqVersion);
if(version.length > reqVersion.length)
{
Integer diff = version.length - reqVersion.length;
strReqVersion += StringUtils.repeat(".0", diff);
}
else if(reqVersion.length > version.length)
{
Integer diff = reqVersion.length - version.length;
strVersion += StringUtils.repeat(".0", diff);
}
return strReqVersion.compareTo(strVersion) < 0;
}
private static boolean isBetween(String[] version, String[] reqVersion)
{
return (isEqual(version, reqVersion) || isHigher(version, reqVersion)) &&
isLess(getNextVersion(version), reqVersion);
}
private static String[] getNextVersion(String[] version)
{
String[] nextVersion = new String[version.length];
for(int i = version.length - 1; i >= 0 ; i--)
{
if(i == version.length - 1)
{
nextVersion[i] = "0";
}
else if((i == version.length - 2) && NumberUtils.isNumber(version[i]))
{
nextVersion[i] = String.valueOf(NumberUtils.toInt(version[i]) + 1);
}
else
{
nextVersion[i] = version[i];
}
}
return nextVersion;
}
由于本页上没有答案能很好地处理混合文本,我做了自己的版本:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Main {
static double parseVersion(String v) {
if (v.isEmpty()) {
return 0;
}
Pattern p = Pattern.compile("^(\\D*)(\\d*)(\\D*)$");
Matcher m = p.matcher(v);
m.find();
if (m.group(2).isEmpty()) {
// v1.0.0.[preview]
return -1;
}
double i = Integer.parseInt(m.group(2));
if (!m.group(3).isEmpty()) {
// v1.0.[0b]
i -= 0.1;
}
return i;
}
public static int versionCompare(String str1, String str2) {
String[] v1 = str1.split("\\.");
String[] v2 = str2.split("\\.");
int i = 0;
for (; i < v1.length && i < v2.length; i++) {
double iv1 = parseVersion(v1[i]);
double iv2 = parseVersion(v2[i]);
if (iv1 != iv2) {
return iv1 - iv2 < 0 ? -1 : 1;
}
}
if (i < v1.length) {
// "1.0.1", "1.0"
double iv1 = parseVersion(v1[i]);
return iv1 < 0 ? -1 : (int) Math.ceil(iv1);
}
if (i < v2.length) {
double iv2 = parseVersion(v2[i]);
return -iv2 < 0 ? -1 : (int) Math.ceil(iv2);
}
return 0;
}
public static void main(String[] args) {
System.out.println("versionCompare(v1.0.0, 1.0.0)");
System.out.println(versionCompare("v1.0.0", "1.0.0")); // 0
System.out.println("versionCompare(v1.0.0b, 1.0.0)");
System.out.println(versionCompare("v1.0.0b", "1.0.0")); // -1
System.out.println("versionCompare(v1.0.0.preview, 1.0.0)");
System.out.println(versionCompare("v1.0.0.preview", "1.0.0")); // -1
System.out.println("versionCompare(v1.0, 1.0.0)");
System.out.println(versionCompare("v1.0", "1.0.0")); // 0
System.out.println("versionCompare(ver1.0, 1.0.1)");
System.out.println(versionCompare("ver1.0", "1.0.1")); // -1
}
}
不过,在需要比较“alpha”和“beta”的情况下,它仍然不够。
我喜欢@Peter Lawrey的想法,我把它扩展到更远的范围:
/**
* Normalize string array,
* Appends zeros if string from the array
* has length smaller than the maxLen.
**/
private String normalize(String[] split, int maxLen){
StringBuilder sb = new StringBuilder("");
for(String s : split) {
for(int i = 0; i<maxLen-s.length(); i++) sb.append('0');
sb.append(s);
}
return sb.toString();
}
/**
* Removes trailing zeros of the form '.00.0...00'
* (and does not remove zeros from, say, '4.1.100')
**/
public String removeTrailingZeros(String s){
int i = s.length()-1;
int k = s.length()-1;
while(i >= 0 && (s.charAt(i) == '.' || s.charAt(i) == '0')){
if(s.charAt(i) == '.') k = i-1;
i--;
}
return s.substring(0,k+1);
}
/**
* Compares two versions(works for alphabets too),
* Returns 1 if v1 > v2, returns 0 if v1 == v2,
* and returns -1 if v1 < v2.
**/
public int compareVersion(String v1, String v2) {
// Uncomment below two lines if for you, say, 4.1.0 is equal to 4.1
// v1 = removeTrailingZeros(v1);
// v2 = removeTrailingZeros(v2);
String[] splitv1 = v1.split("\\.");
String[] splitv2 = v2.split("\\.");
int maxLen = 0;
for(String str : splitv1) maxLen = Math.max(maxLen, str.length());
for(String str : splitv2) maxLen = Math.max(maxLen, str.length());
int cmp = normalize(splitv1, maxLen).compareTo(normalize(splitv2, maxLen));
return cmp > 0 ? 1 : (cmp < 0 ? -1 : 0);
}
希望它能帮助到别人。它通过了interviewbit和leetcode中的所有测试用例(需要取消compareVersion函数中的两行注释)。
很容易测试!
如果你的项目中已经有Jackson,你可以使用com.fasterxml.jackson.core.Version:
import com.fasterxml.jackson.core.Version;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class VersionTest {
@Test
public void shouldCompareVersion() {
Version version1 = new Version(1, 11, 1, null, null, null);
Version version2 = new Version(1, 12, 1, null, null, null);
assertTrue(version1.compareTo(version2) < 0);
}
}