James Manes
James Manes

Reputation: 526

Java Regex: Extracting a Version Number

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?

Upvotes: 1

Views: 5593

Answers (4)

Pshemo
Pshemo

Reputation: 124225

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(' ')));

Upvotes: 1

greedybuddha
greedybuddha

Reputation: 7507

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

Upvotes: 1

arshajii
arshajii

Reputation: 129507

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

Upvotes: 1

jlordo
jlordo

Reputation: 37813

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);

Upvotes: 3

Related Questions