我正在研究一种从字符串中提取正确版本号的方法(如果有新版本供以后比较)。
不幸的是,提供的字符串没有固定的模式,可以有多种数字组合。
下面的代码解析版本号,但如果字符串包括例如build 50124 ,则此数字将粘贴在我不想要的提取版本组合之后。
也可能是字符串中的组合是可能的,例如 v1.12 [build452] 或 v1.32.856(build 8754),但我已经通过将 [ 或 (.
有问题的方法:
private String extractVersion(String str){
str = str.substring(str.lastIndexOf('v'),
str.indexOf('[') != -1 ? str.indexOf('[') : str.length()).trim();
str = str.substring(str.lastIndexOf('v'),
str.indexOf('(') != -1 ? str.indexOf('(') : str.length()).trim();
return str.replaceAll("[^0-9?!\\.]", "");
}
我在一些示例上对其进行了测试,但不幸的是结果不是我想要的,有时会在实际版本号后面粘贴数字,我指的是logcat 输出。
是否有“更好的”正则表达式或其他方法可以用来改进该方法,以便提取正确的版本号?
谢谢您的帮助。
..
NewVersion = tempWatchList.get(i);
Log.w("Versionnr", extractVersion(NewVersion));
Log.e("Versionname", NewVersion);
..
Logcat 输出:
/Versionnr: 5.131 //should be 5.13
/Versionname: somename v5.13b1
/Versionnr: 2.0..4 //should be 2.0
/Versionname: another name 2 v2.0.exp.4
/Versionnr: 18.01 //should be 18.0
/Versionname: somename v18.0-ALPHA1
/Versionnr: 7.2.42221..3634639 //should be 7.2.4222
/Versionname: another name v7.2.4222-1.L.3634639
/Versionnr: 5.0.220170112 //should be 5.0.2
/Versionname: somename v5.0.2 build 20170112
/Versionnr: 4.4.0.201701124401 //should be 4.4.0
/Versionname: another name v4.4.0.20170112b4401