0

This is my code in which I am trying to enter an IP Adress and check if it matches with the guidelines - Number of digits less than 3, and numbers between 0-255. Eg - 111.245.0.11 But every time I run the program, the matches method is outputting false, whatever be the input.

MAIN CLASS

package Rough;

import java.util.Scanner;
public class Regex
{
    public static void main(String args[])throws Exception
    {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNextLine())
        {
            String ip = sc.next();
            System.out.println(ip.matches(new MyRegex().pattern));
        }
    }
}

MYRegex Class

package Rough;
public class MyRegex extends Regex
{
    String limit = "(\\d{1,2} | (0,1)\\d{2} | 2[0-4]\\d | 25[0-5])";
    public String pattern = limit+"\\."+ limit + "\\."+ limit + "\\." + limit;
}
  • Well, have you tested that "limit" matches a single number yet? (I'm concerned that the spaces may well be relevant.) It's not clear why these are instance fields, either... – Jon Skeet Oct 13 '17 at 08:49
  • 1
    In the ``limit`` variable, you use ``(0,1)\\d{2}``. The comma is treated as a literal and since a comma is not present in an ip adress, the matching fails. You probably want ``(0|1)\\d{2}`` or ``[01]\\d{2}`` instead. – f1sh Oct 13 '17 at 08:49
  • Check this example: https://www.mkyong.com/regular-expressions/how-to-validate-ip-address-with-regular-expression/ – Yogi Oct 13 '17 at 09:08

0 Answers0