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
  • DSA
  • Practice Searching Algorithms
  • MCQs on Searching Algorithms
  • Tutorial on Searching Algorithms
  • Linear Search
  • Binary Search
  • Ternary Search
  • Jump Search
  • Sentinel Linear Search
  • Interpolation Search
  • Exponential Search
  • Fibonacci Search
  • Ubiquitous Binary Search
  • Linear Search Vs Binary Search
  • Interpolation Search Vs Binary Search
  • Binary Search Vs Ternary Search
  • Sentinel Linear Search Vs Linear Search
Open In App
Next Article:
How to validate ISIN using Regular Expressions
Next article icon

How to validate an IP address using ReGex

Last Updated : 15 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an IP address, the task is to validate this IP address with the help of Regex (Regular Expression) in C++ as a valid IPv4 address or IPv6 address. If the IP address is not valid then print an invalid IP address.

Examples: 

Input: str = “203.120.223.13” 
Output: Valid IPv4

Input: str = “000.12.234.23.23” 
Output: Invalid IP

Input: str = “2F33:12a0:3Ea0:0302” 
Output: Invalid IP

Input: str = “I.Am.not.an.ip” 
Output: Invalid IP 

Approach:

  • Regex (Regular Expression) In C++ will be used to check the IP address.
  • Range Specifications 
    Specifying a range of characters or literals is one of the simplest criteria used in a regex.
i) [a-z] ii) [A-Za-z0-9]
  • In the above expression ([]) square brackets are used to specify the range.
  • The first expression will match exactly one lowercase character.
  • The second expression specifies the range containing one single uppercase character, one lowercase character, and a digit from 0 to 9.
  • Now to include a ‘.’ as part of an expression, we need to escape ‘.’ and this can be done as :
[\\.0-9]

The above expression indicates an ‘.’ and a digit in the range 0 to 9 as a regex.

  • regex_match() function is used to match the given pattern. This function returns true if the given expression matches the string. Otherwise, the function returns false.

Here is the implementation of the above approach. 

C++




// C++ program to validate
// IP address using Regex
 
#include <bits/stdc++.h>
using namespace std;
 
// Function for Validating IP
string Validate_It(string IP)
{
 
    // Regex expression for validating IPv4
    regex ipv4("(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])");
 
    // Regex expression for validating IPv6
    regex ipv6("((([0-9a-fA-F]){1,4})\\:){7}([0-9a-fA-F]){1,4}");
 
    // Checking if it is a valid IPv4 addresses
    if (regex_match(IP, ipv4))
        return "Valid IPv4";
 
    // Checking if it is a valid IPv6 addresses
    else if (regex_match(IP, ipv6))
        return "Valid IPv6";
 
    // Return Invalid
    return "Invalid IP";
}
 
// Driver Code
int main()
{
    // IP addresses to validate
    string IP = "257.120.223.13";
    cout << Validate_It(IP) << endl;
 
    IP = "fffe:3465:efab:23fe:2235:6565:aaab:0001";
    cout << Validate_It(IP) << endl;
 
    IP = "2F33:12a0:3Ea0:0302";
    cout << Validate_It(IP) << endl;
 
    return 0;
}
 
 

Java




// Java program to validate
// IP address using Regex
import java.util.regex.*;
 
class GFG {
 
  // Function for Validating IP
  static String Validate_It(String IP)
  {
 
    // Regex expression for validating IPv4
    String regex="(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])";
 
    // Regex expression for validating IPv6
    String regex1="((([0-9a-fA-F]){1,4})\\:){7}([0-9a-fA-F]){1,4}";
 
    Pattern p = Pattern.compile(regex);
    Pattern p1 = Pattern.compile(regex1);
 
    // Checking if it is a valid IPv4 addresses
    if (p.matcher(IP).matches())
      return "Valid IPv4";
 
    // Checking if it is a valid IPv6 addresses
    else if (p1.matcher(IP).matches())
      return "Valid IPv6";
 
    // Return Invalid
    return "Invalid IP";
  }
 
  // Driver Code
  public static void main(String args[])
  {
    // IP addresses to validate
    String IP = "257.120.223.13";
    System.out.println(Validate_It(IP));
 
    IP = "fffe:3465:efab:23fe:2235:6565:aaab:0001";
    System.out.println(Validate_It(IP));
 
    IP = "2F33:12a0:3Ea0:0302";
    System.out.println(Validate_It(IP));
 
  }
}
 
// This code is contributed by Aman Kumar.
 
 

Python3




# Python3 program to validate
# IP address using Regex
import re
 
# Function for Validating IP
 
 
def Validate_It(IP):
 
    # Regex expression for validating IPv4
    regex = "^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$"
 
    # Regex expression for validating IPv6
    regex1 = "((([0-9a-fA-F]){1,4})\\:){7}"\
             "([0-9a-fA-F]){1,4}"
 
    p = re.compile(regex)
    p1 = re.compile(regex1)
 
    # Checking if it is a valid IPv4 addresses
    if (re.search(p, IP)):
        return "Valid IPv4"
 
    # Checking if it is a valid IPv6 addresses
    elif (re.search(p1, IP)):
        return "Valid IPv6"
 
    # Return Invalid
    return "Invalid IP"
 
# Driver Code
 
 
# IP addresses to validate
IP = "257.120.223.13"
print(Validate_It(IP))
 
IP = "fffe:3465:efab:23fe:2235:6565:aaab:0001"
print(Validate_It(IP))
 
IP = "2F33:12a0:3Ea0:0302"
print(Validate_It(IP))
 
# This code is contributed by avanitrachhadiya2155
 
 

C#




// C# program to validate
// IP address using Regex
using System;
using System.Text.RegularExpressions;
 
class GFG {
 
// Function for Validating IP
static string Validate_It(string IP)
{
 
    // Regex expression for validating IPv4
    string regex="(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])";
 
    // Regex expression for validating IPv6
    string regex1="((([0-9a-fA-F]){1,4})\\:){7}([0-9a-fA-F]){1,4}";
 
    Regex p = new Regex(regex);
    Regex p1 = new Regex(regex1);
 
    // Checking if it is a valid IPv4 addresses
    if (p.IsMatch(IP))
    return "Valid IPv4";
 
    // Checking if it is a valid IPv6 addresses
    else if (p1.IsMatch(IP))
    return "Valid IPv6";
 
    // Return Invalid
    return "Invalid IP";
}
 
// Driver Code
public static void Main()
{
    // IP addresses to validate
    string IP = "257.120.223.13";
    Console.WriteLine(Validate_It(IP));
 
    IP = "fffe:3465:efab:23fe:2235:6565:aaab:0001";
    Console.WriteLine(Validate_It(IP));
 
    IP = "2F33:12a0:3Ea0:0302";
    Console.WriteLine(Validate_It(IP));
 
}
}
 
// This code is contributed by Pushpesh Raj.
 
 

Javascript




// JavaScript program to validate
// IP address using Regex
 
// Function for Validating IP
function Validate_It(IP) {
 
    // Regex expression for validating IPv4
    let ipv4 = /(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])/;
 
    // Regex expression for validating IPv6
    let ipv6 = /((([0-9a-fA-F]){1,4})\:){7}([0-9a-fA-F]){1,4}/;
 
    // Checking if it is a valid IPv4 addresses
    if (IP.match(ipv4))
        return "Valid IPv4";
 
    // Checking if it is a valid IPv6 addresses
    else if (IP.match(ipv6))
        return "Valid IPv6";
 
    // Return Invalid
    return "Invalid IP";
}
 
// Driver Code
function main() {
    // IP addresses to validate
    let IP = "257.120.223.13";
    console.log(Validate_It(IP));
 
    IP = "fffe:3465:efab:23fe:2235:6565:aaab:0001";
    console.log(Validate_It(IP));
 
    IP = "2F33:12a0:3Ea0:0302";
    console.log(Validate_It(IP));
}
 
main();
 
// This code is contributed by akashish__
 
 
Output
Invalid IP Valid IPv6 Invalid IP

Time Complexity: O (N) 
Auxiliary Space: O (1)
 



Next Article
How to validate ISIN using Regular Expressions

A

abhishek_padghan
Improve
Article Tags :
  • Computer Networks
  • DSA
  • Searching
  • Strings
  • CPP-regex
  • IP Addressing
  • java-regular-expression
  • python-regex
  • regular-expression
Practice Tags :
  • Searching
  • Strings

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
  • Program to validate an IP address
    Write a program to Validate an IP Address. An IP address is a unique identifier for devices on a network, enabling internet communication. It has two versions: IPv4 and IPv6. We will validate IPv4 and IPv6 addresses separately. Table of Content IPv4 Addresses ValidationIPv6 Addresses ValidationIPv4
    15+ 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 an IP address using Regular Expressions in Java
    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: Inpu
    3 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 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 SWIFT/BIC Code Using RegEx?
    A SWIFT/BIC code consists of 8-11 characters SWIFT follows a format that identifies your bank, country, location, and branch. A SWIFT code — is also called a BIC number.BIC is a standard format for Business Identifier Codes (BIC). It’s used to identify banks and financial institutions globally. Thes
    7 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 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