3

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 correctly
  • Windows Server 2008 - Matches correctly
  • Windows Server 2008 R2 Datacenter - Does not match
  • Windows Server 2008 r2 datacenter - Does not match
  • Windows Server 2008 R2 - Matches incorrectly (because R2 fits into \w* in the regex)

What am I doing wrong in the regex?

2
  • Remove the \s* after your lookahead. Are you using this in context of String matches()? Commented Mar 10, 2017 at 15:10
  • No. I am using pattern.matcher from java.util.regex. But removing \s worked for regex matcher too. Thanks Commented Mar 11, 2017 at 10:35

2 Answers 2

1

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());
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.