简体   繁体   中英

Java regex to extract version

I am trying to write a java regex to strip off java version from string I get from java -version command.

If the string is "java version 1.7.0_17" I need to extract 1.7 and 17 separately. Suppose if the string is "java version 1.06_18" I need to extract 1.06 and 18. Where first string should be only till the first decimal point. I tried with the below regex,

Pattern p = Pattern.compile(".*\"(.+)_(.+)\"");

But it extracts only 1.7.0 and 17, but I not sure how to stop still one decimal point. Any help will be really appreciable.

对于您给出的测试用例,可以使用以下命令: (\\d+\\.\\d+).*_(\\d+)

Re-read your question, my old answer didn't cover stopping at the first decimal point. This should solve your problem:

Pattern p = Pattern.compile(".*?(\\d+[.]\\d+).*?_(\\d+)");

Tested:

 String input = "java version 1.7.0_17";
 Pattern pattern = Pattern.compile(".*?(\\d+[.]\\d+).*?_(\\d+)");
 Matcher matcher = pattern.matcher(input);
 if (matcher.find()) {
     String version = matcher.group(1); // 1.7
     String update  = matcher.group(2); // 17
}

Old version:

Instead of finding the numbers, I'd get rid of the rest:

String string  = "java version 1.7.0_17";
String[] parts = string.split("[\\p{Alpha}\\s_]+", -1);
String version = parts[1]; // 1.7.0
String update  = parts[2]; // 17

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM