Java Regex: Extracting a Version Number

故事扮演 提交于 2020-01-05 08:15:53

问题


I have a program that stores the version number in a text file on the file system. I import the file within java and I am wanting to extract the version number. I'm not very good with regex so I am hoping someone can help.

The text file looks like such:

0=2.2.5 BUILD (tons of other junk here)

I am wanting to extract 2.2.5. Nothing else. Can someone help me with the regex for this?


回答1:


If you know the structure, you don't need a regex:

    String line = "0=2.2.5 BUILD (tons of other junk here)";
    String versionNumber = line.split(" ", 2)[0].substring(2);



回答2:


This regular expression should do the trick:

(?<==)\d+\.\d+\.\d+(?=\s*BUILD)

Trying it out:

String s = "0=2.2.5 BUILD (tons of other junk here)";

Pattern p = Pattern.compile("(?<==)\\d+\\.\\d+\\.\\d+(?=\\s*BUILD)");
Matcher m = p.matcher(s);
while (m.find())
    System.out.println(m.group());
2.2.5



回答3:


Also if you are really looking for a regex, though there are definitely many ways to do this.

String line = "0=2.2.5 BUILD (tons of other junk here)";
Matcher matcher = Pattern.compile("^\\d+=((\\d|\\.)+)").matcher(line);
if (matcher.find())
    System.out.println(matcher.group(1));

Output:

2.2.5



回答4:


There are many ways to do this. Here is one of them

String data = "0=2.2.5 BUILD (tons of other junk here)";
Matcher m = Pattern.compile("\\d+=(\\d+([.]\\d+)+) BUILD").matcher(data);
if (m.find())
    System.out.println(m.group(1));

If you are sure that data contains version number then you can also

System.out.println(data.substring(data.indexOf('=')+1,data.indexOf(' ')));


来源:https://stackoverflow.com/questions/17052017/java-regex-extracting-a-version-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!