Reputation: 1494
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
Reputation: 2155
Proposal:
"(version)\\s(1(\\.0)?)([^\\.0-9].*|$)"
Upvotes: 0
Reputation: 785246
If you have version
string in a longer string then use this lookahead regex:
\bversion\s+1(?:\.0)?(?=\s|$)
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