1

I'm attempting to check if a string contains only

  • 1

  • 0

  • .

or a combination of these three.

First I had this code:

public static boolean controleSubnetmask(String mask) {
    try {
        String[] maskArray = mask.split(".");
        int[] subnetmask = new int[4];

        //array of string to array of int
        for (int i = 0; i < maskArray.length; i++) {
            subnetmask[i] = Integer.parseInt(maskArray[i]);
        }
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}

but that is rather complicated for what it does, and it doesn't check if only 1 and 0 are entered. So now I have this, but it seems I misunderstood regular expressions because it doesn't work:

public static void controleSubnetmask(String mask) {
    mask = "1100.110...11";
    String test = "p";
    if (mask.contains("[^10\\.]") == true) {
        System.out.println("wrong input");
    }
    if (test.contains("[^10\\.]") == true) {
        System.out.println("wrong input");
    }
}

I expected a 'wrong input' message on the test String, which didn't appear. So I believe my regex:

[^01\\.]

is wrong, but I really have no clue how to specify it. Thanks in advance!

Bjorn De Rijcke
  • 653
  • 10
  • 23
  • Your regex `[^10\\.]` says "The string starts with a 1 followed by a 0 and a dot". Just rethink what you want to achieve. Additionally contains() might not be the proper method for the purpose. Refer [javadoc](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#contains(java.lang.CharSequence)). – Dhrubajyoti Gogoi May 27 '14 at 12:31

1 Answers1

5

String.contains works with Strings NOT with REGEX. use String.matches instead. As @lazy points out, you could use Pattern and Matcher classes as well.

test.contains("[^10\\.]") == true 

All you are doing here is checking whether test contains the String literals [^10\.]

TheLostMind
  • 35,966
  • 12
  • 68
  • 104