Kundan Chaudhary
Kundan Chaudhary

Reputation: 833

ip address in java valid or not

I want to validate IP address with or without a port number using regex. My input string would be IP:PORT or just IP. I want only one regex which will be validating IP:PORT or IP both.

My IP address regex is:

^(?:(?:1\d?\d|[1-9]?\d|2[0-4]\d|25[0-5])\.){3}(?:1\d?\d|[1-9]?\d|2[0-4]\d|25[0-5])$

Can someone let me know how to add optional port numbers to this existing regex?

Upvotes: 1

Views: 2618

Answers (4)

busetekin
busetekin

Reputation: 854

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 {

                                           String pattern="^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +

                                                                          "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +

                                                                          "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +

                                                                          "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";

            }

private static final String IPADDRESS_PATTERN =

                           "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +

                           "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +

                           "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +

                           "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";

ı used this solution from this website:

https://www.mkyong.com/regular-expressions/how-to-validate-ip-address-with-regular-expression/

Upvotes: 1

Sri Harsha Chilakapati
Sri Harsha Chilakapati

Reputation: 11940

This works.

^(?:(?:1\d?\d|[1-9]?\d|2[0-4]\d|25[0-5])\.){3}(?:1\d?\d|[1-9]?\d|2[0-4]\d|25[0-‌​5])(?:[:]\d+)?$ 

Upvotes: 1

rolfl
rolfl

Reputation: 17707

Why so complicated: Google for it: http://answers.oreilly.com/topic/318-how-to-match-ipv4-addresses-with-regular-expressions/

You are also trying to do too much in one place. Use the regex for what it's good for, and then use other smarts for the places where regex is not the right tool. In your case, don't try to validate the value ranges for the IP address in the regex, but in the post-process:

.... ^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(:(\d{1,5}))?$

byte[] ip = new byte[4];
for (int i = 1; i <= 4; i++) {
    int bt = Integer.parseInt(matcher.group(i));
    if (bt < 0 || bt > 255) {
       throw new IllegalArgumentException("Byte value " + bt + " is not valid.");
    }
    ip[i-1] = (byte)bt;
}
integer port = 0;
if (matcher.group(6) != null) {
  port = Integer.parseInt(matcher.group(6));
}

Upvotes: 1

AlexR
AlexR

Reputation: 115328

Use trailing ? to mark optional part, i.e. add (:\\d+) to the end of your regex.

Upvotes: 0

Related Questions