Reputation: 31
I want to find a regex in Java for a Windows Server 2008 OS version which does not contain "R2" Regex I am currently using -
(?i)Win\w*\s*(?i)Server\s*(2008)\s*(?!R2)\s*\w*
Possible values:
Windows Server 2008 datacenter
- Matches correctlyWindows Server 2008
- Matches correctlyWindows Server 2008 R2 Datacenter
- Does not matchWindows Server 2008 r2 datacenter
- Does not matchWindows Server 2008 R2
- Matches incorrectly (because R2
fits into \w*
in the regex)What am I doing wrong in the regex?
Upvotes: 3
Views: 1525
Reputation: 4523
You may consider using the following regex :
(?i)Win\w*\s*Server\s*(2008)(?!\sR2).*?$
see regex demo
Java ( demo )
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class RegEx {
public static void main(String[] args) {
String s = "Windows Server 2008 datacenter";
String r = "(?i)Win\\w*\\s*Server\\s*(2008)(?!\\sR2).*?$";
Pattern p = Pattern.compile(r);
Matcher m = p.matcher(s);
while (m.find()) {
System.out.println(m.group());
}
}
}
Upvotes: 1
Reputation: 13910
Regular expression to match string if it contains R2
private boolean isR2(String text) {
return (text.toLowerCase().matches(".*r2.*"));
}
without regular expression, you can do
private boolean isR2(String text) {
return (text.toLowerCase().indexOf("r2")>0);
}
both match all your examples correctly:
Windows Server 2008 datacenter // false
Windows Server 2008 //false
Windows Server 2008 R2 Datacenter //true
Windows Server 2008 r2 datacenter //true
Windows Server 2008 R2 //true
Upvotes: 0