In my coding challenge I have the following problem:
Write a class called MyRegex which will contain a string pattern. You need to write a regular expression and assign it to the pattern such that it can be used to validate an IP address. Use the following definition of an IP address:
IP address is a string in the form "A.B.C.D", where the value of A, B, C, and D may range from 0 to 255. Leading zeros are allowed. The length of A, B, C, or D can't be greater than 3.
I looked up here beacuse I've never worked with patterns...
After a while I looked up whats the solution and a valid one is this:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Scanner;
class Solution{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
while(in.hasNext()){
String IP = in.next();
System.out.println(IP.matches(new MyRegex().pattern));
}
}
}
class MyRegex {
public String pattern = "((\\d|\\d\\d|[0-1]\\d\\d|2[0-4][0-9]|25[0-5])\\.){3}(\\d|\\d\\d|[0-1]\\d\\d|2[0-4][0-9]|25[0-5])";
}
Why is this working? What do the backslashes do and why are there dots etc. because when I read in the oracle docs, "\" is just a backslash and "." just means "any character" but according to the problem, the input should not contain just any characters so I don't understand this solution ... Whats going on here ?