appu_coder
appu_coder

Reputation: 31

Java- Regex for a string not containing a substring followed by any characters

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:

What am I doing wrong in the regex?

Upvotes: 3

Views: 1525

Answers (2)

m87
m87

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

Eddie Martinez
Eddie Martinez

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

Related Questions