RonPringadi
RonPringadi

Reputation: 1494

Java regex for detecting version with optional period

I'm trying to find a proper regex in java to detect all version 1 from large content. And I only care with just version 1, version 1.0, or version 1.0 but not 1.1. The test string can then be followed any other character or end of line.

How do I do that in java?

Thanks in advance

    String regex="(version)(\\s)(1|1\\.0)";
    Pattern p = Pattern.compile(regex);
    Matcher m   = null;

    String testString1="version 1";
    m = p.matcher(testString1);
    System.out.println (m.find());

    String testString2="version 1.0";
    m = p.matcher(testString2);
    System.out.println (m.find());

    String testString3="version 1.1";  // should not match
    m = p.matcher(testString3);
    System.out.println (m.find());

Upvotes: 2

Views: 634

Answers (2)

pintxo
pintxo

Reputation: 2155

Proposal:

"(version)\\s(1(\\.0)?)([^\\.0-9].*|$)"
  1. The string "version" needs to be present
  2. followed by any whitespace
  3. then a single "1"
  4. optionally followed by ".0"
  5. and the next char either (cannot be "." or any digit (think 1.01 is forbidden, as well as 1.0.1)) or (is the end of the string)

Upvotes: 0

anubhava
anubhava

Reputation: 785246

If you have version string in a longer string then use this lookahead regex:

\bversion\s+1(?:\.0)?(?=\s|$)

RegEx Demo

In Java:

final String regex = "\\bversion\\s+1(?:\\.0)?(?=\\s|$)";

(?=\\s|$) is positive lookahead to assert that we have a whitespace or line end after version number.

Upvotes: 1

Related Questions