Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to validate MAC address using Regular Expression
Next article icon

How to validate an IP address using Regular Expressions in Java

Last Updated : 10 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an IP address, the task is to validate this IP address with the help of Regular Expressions.
The 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.
Examples: 
 

Input: str = "000.12.12.034" Output: True  Input: str = "000.12.234.23.23" Output: False  Input: str = "121.234.12.12" Output: True  Input: str = "I.Am.not.an.ip" Output: False

 

Approach: 
In this article, the IP address is validated with the help of Regular Expressions or Regex. Below are the steps to solve this problem using ReGex:
 

  1. Get the string.
  2. Regular expression to validate an IP address: 
     
// ReGex to numbers from 0 to 255 zeroTo255 -> (\\d{1, 2}|(0|1)\\d{2}|2[0-4]\\d|25[0-5])  // ReGex to validate complete IP address IPAddress -> zeroTo255 + "\\." + zeroTo255                  + "\\." + zeroTo255                  + "\\." + zeroTo255;
  1. where: 
    • \d represents digits in regular expressions, same as [0-9]
    • \\d{1, 2} catches any one or two-digit number
    • (0|1)\\d{2} catches any three-digit number starting with 0 or 1.
    • 2[0-4]\\d catches numbers between 200 and 249.
    • 25[0-5] catches numbers between 250 and 255.
  2. Match the string with the Regex. In Java, this can be done using Pattern.matcher(). 
     
  3. Return true if the string matches with the given regex, else return false.

Below is the implementation of the above approach:
 

Java




// Java program to validate an IP address
// using Regular Expression or ReGex
 
import java.util.regex.*;
 
class IPAddressValidation {
 
    // Function to validate the IPs address.
    public static boolean isValidIPAddress(String ip)
    {
 
        // Regex for digit from 0 to 255.
        String zeroTo255
            = "(\\d{1,2}|(0|1)\\"
              + "d{2}|2[0-4]\\d|25[0-5])";
 
        // Regex for a digit from 0 to 255 and
        // followed by a dot, repeat 4 times.
        // this is the regex to validate an IP address.
        String regex
            = zeroTo255 + "\\."
              + zeroTo255 + "\\."
              + zeroTo255 + "\\."
              + zeroTo255;
 
        // Compile the ReGex
        Pattern p = Pattern.compile(regex);
 
        // If the IP address is empty
        // return false
        if (ip == null) {
            return false;
        }
 
        // Pattern class contains matcher() method
        // to find matching between given IP address
        // and regular expression.
        Matcher m = p.matcher(ip);
 
        // Return if the IP address
        // matched the ReGex
        return m.matches();
    }
 
    // Driver code
    public static void main(String args[])
    {
        // Checking for True case.
        // Test Case: 1
        System.out.println("Test Case 1:");
        String str1 = "000.12.12.034";
        System.out.println("Input: " + str1);
        System.out.println(
            "Output: "
            + isValidIPAddress(str1));
 
        // Test Case: 2
        System.out.println("\nTest Case 2:");
        String str2 = "121.234.12.12";
        System.out.println("Input: " + str2);
        System.out.println(
            "Output: "
            + isValidIPAddress(str2));
 
        // Checking for False case.
        // Test Case: 3
        System.out.println("\nTest Case 3:");
        String str3 = "000.12.234.23.23";
        System.out.println("Input: " + str3);
        System.out.println(
            "Output: "
            + isValidIPAddress(str3));
 
        // Test Case: 4
        System.out.println("\nTest Case 4:");
        String str4 = "I.Am.not.an.ip";
        System.out.println("Input: " + str4);
        System.out.println(
            "Output: "
            + isValidIPAddress(str4));
    }
}
 
 
Output: 
Test Case 1: Input: 000.12.12.034 Output: true  Test Case 2: Input: 121.234.12.12 Output: true  Test Case 3: Input: 000.12.234.23.23 Output: false  Test Case 4: Input: I.Am.not.an.ip Output: false

 



Next Article
How to validate MAC address using Regular Expression
author
prashant_srivastava
Improve
Article Tags :
  • Computer Networks
  • Java
  • Technical Scripter
  • java-regular-expression
  • Technical Scripter 2019
Practice Tags :
  • Java

Similar Reads

  • How to validate MAC address using Regular Expression
    Given string str, the task is to check whether the given string is a valid MAC address or not by using Regular Expression. A valid MAC address must satisfy the following conditions: It must contain 12 hexadecimal digits.One way to represent them is to form six pairs of the characters separated with
    6 min read
  • How to validate a Username using Regular Expressions in Java
    Given a string str which represents a username, the task is to validate this username with the help of Regular Expressions. A username is considered valid if all the following constraints are satisfied: The username consists of 6 to 30 characters inclusive. If the username consists of less than 6 or
    3 min read
  • How to Validate Email Address without using Regular Expression in JavaScript ?
    Email validation in JavaScript is the process of ensuring that an email address entered by the user is in the correct format and is a valid email address or not. This is typically done on the client side using JavaScript before the form is submitted to the server. An email address must have the foll
    5 min read
  • How to Validate a Password using Regular Expressions in Android?
    Regular Expression basically defines a search pattern, pattern matching, or string matching. It is present in java.util.regex package. Java Regex API provides 1 interface and 3 classes. They are the following: MatchResult InterfaceMatcher classPattern classPatternSyntaxException class Pattern p = Pa
    4 min read
  • How to validate a domain name using Regular Expression
    Given string str, the task is to check whether the given string is a valid domain name or not by using Regular Expression.The valid domain name must satisfy the following conditions: The domain name should be a-z or A-Z or 0-9 and hyphen (-).The domain name should be between 1 and 63 characters long
    6 min read
  • How to validate ISIN using Regular Expressions
    ISIN stands for International Securities Identification Number. Given string str, the task is to check whether the given string is a valid ISIN(International Securities Identification Number) or not by using Regular Expression. The valid ISIN(International Securities Identification Number) must sati
    6 min read
  • How to validate PAN Card number using Regular Expression
    Given string str of alphanumeric characters, the task is to check whether the string is a valid PAN (Permanent Account Number) Card number or not by using Regular Expression.The valid PAN Card number must satisfy the following conditions: It should be ten characters long.The first five characters sh
    6 min read
  • How to Validate MICR Code using Regular Expression?
    MICR stands for Magnetic Ink Character Recognition. This technology provides transaction security, ensuring the correctness of bank cheques. MICR code makes cheque processing faster and safer. MICR Technology reduces cheque-related fraudulent activities. Structure of a Magnetic Ink Character Recogni
    6 min read
  • How to validate IFSC Code using Regular Expression
    Given string str, the task is to check whether the given string is a valid IFSC (Indian Financial System) Code or not by using Regular Expression. The valid IFSC (Indian Financial System) Code must satisfy the following conditions: It should be 11 characters long.The first four characters should be
    8 min read
  • How to validate pin code of India using Regular Expression
    Given a string of positive number ranging from 0 to 9, the task is to check whether the number is valid pin code or not by using a Regular Expression. The valid pin code of India must satisfy the following conditions. It can be only six digits.It should not start with zero.First digit of the pin cod
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences