Java Regex: Extracting a Version Number

2019-08-04 13:54发布

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?

4条回答
劳资没心,怎么记你
2楼-- · 2019-08-04 14:00

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(' ')));
查看更多
戒情不戒烟
3楼-- · 2019-08-04 14:05

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楼-- · 2019-08-04 14:11

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
查看更多
走好不送
5楼-- · 2019-08-04 14:22

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);
查看更多
登录 后发表回答