Extracting IP Address From a Given String Using Regular Expressions
Last Updated :
20 Sep, 2023
Prerequisites:
Given a string str, the task is to extract all the IP addresses from the given string. Let us see how to extract IP addresses from a file.
Input:
str="The IPV4 address of Port A is: 257.120.223.13. And the IPV6 address is:fffe:3465:efab:23fe:2235:6565:aaab:0001"
Output:
257.120.223.13
fffe:3465:efab:23fe:2235:6565:aaab:0001
Create a regex pattern to validate the number as written below:
- 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_IPV6="((([0-9a-fA-F]){1,4})\\:){7}([0-9a-fA-F]){1,4}"
Follow the below steps to implement the idea:
- Create a regex expression to extract all the IP Addresses from the string.
- Use Pattern class to compile the regex formed.
- Use the matcher function to find.
Below is the implementation of the above approach:
C++
// C++ Program to Extract IP
// From given string
#include <bits/stdc++.h>
using namespace std;
int main()
{
// String to observe
string subject
= "The IPV4 address of Port A is :257.120.223.13 . "
"And the IPV6 address "
"is:fffe:3465:efab:23fe:2235:6565:aaab:0001";
// Regex for IPV4
regex pattern(
"(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})");
cout << "Available IP Addresses in the Given String Are:"
<< endl;
// Iterating over string to extract all
// IPV4 patterns
for (regex_iterator<string::iterator> it(
subject.begin(), subject.end(), pattern);
it != regex_iterator<string::iterator>(); ++it) {
cout << it->str() << endl;
}
// Regex for IPV6
regex pattern1(
"((([0-9a-fA-F]){1,4})\\:){7}([0-9a-fA-F]){1,4}");
// Iterating over string to extract all
// IPV6 patterns
for (regex_iterator<string::iterator> it(
subject.begin(), subject.end(), pattern1);
it != regex_iterator<string::iterator>(); ++it) {
cout << it->str() << endl;
}
return 0;
}
Java
// Java Program to Extract IP
// From given string
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GFG {
// Driver Code
public static void main(String[] args)
{
// String containing in it
String str
= " The IPV4 address of Port A is :257.120.223.13 . And the IPV6 address is:fffe:3465:efab:23fe:2235:6565:aaab:0001";
System.out.println(
"Available IP Addresses in the Given String Are:");
extractIP_Addresses(str);
}
// Function to extract IP Address
// from a given string
static void extractIP_Addresses(String str)
{
// You can Add n number of Email
// formats in the below given
// String Array.
String strPattern[] = {
"(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})",
"((([0-9a-fA-F]){1,4})\\:){7}([0-9a-fA-F]){1,4}"
};
// Extracting all Patterns from the string
for (int i = 0; i < strPattern.length; i++) {
Pattern pattern
= Pattern.compile(strPattern[i]);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}
}
Python3
import re
# String to observe
subject = ("The IPV4 address of Port A is :257.120.223.13 . "
"And the IPV6 address "
"is:fffe:3465:efab:23fe:2235:6565:aaab:0001")
# Regex for IPV4
pattern_ipv4 = r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b'
print("Available IP Addresses in the Given String Are:")
# Find all IPV4 patterns
ipv4_addresses = re.findall(pattern_ipv4, subject)
for address in ipv4_addresses:
print(address)
# Regex for IPV6
pattern_ipv6 = r'\b(?:[A-Fa-f0-9]{1,4}:){7}[A-Fa-f0-9]{1,4}\b'
# Find all IPV6 patterns
ipv6_addresses = re.findall(pattern_ipv6, subject)
for address in ipv6_addresses:
print(address)
C#
using System;
using System.Text.RegularExpressions;
namespace GFG
{
class Program
{
static void Main(string[] args)
{
// String containing IP addresses
string str = " The IPV4 address of Port A is :257.120.223.13 . And the IPV6 address is:fffe:3465:efab:23fe:2235:6565:aaab:0001";
Console.WriteLine("Available IP Addresses in the Given String Are:");
ExtractIPAddresses(str);
}
static void ExtractIPAddresses(string str)
{
// Patterns for IPV4 and IPV6 addresses
string[] strPattern = {
@"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})",
@"(([0-9a-fA-F]){1,4})\:(([0-9a-fA-F]){1,4})\:(([0-9a-fA-F]){1,4})\:(([0-9a-fA-F]){1,4})\:(([0-9a-fA-F]){1,4})\:(([0-9a-fA-F]){1,4})\:(([0-9a-fA-F]){1,4})\:(([0-9a-fA-F]){1,4})"
};
// Extracting all patterns from the string
for (int i = 0; i < strPattern.Length; i++)
{
Regex pattern = new Regex(strPattern[i]);
MatchCollection matches = pattern.Matches(str);
foreach (Match match in matches)
{
Console.WriteLine(match.Value);
}
}
}
}
}
JavaScript
// String to observe
const subject = "The IPV4 address of Port A is :257.120.223.13 . And the IPV6 address is:fffe:3465:efab:23fe:2235:6565:aaab:0001";
// Regex for IPV4
const pattern = /(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/g;
console.log("Available IP Addresses in the Given String Are:");
// Iterating over string to extract all IPV4 patterns
let match;
while ((match = pattern.exec(subject)) !== null) {
console.log(match[0]);
}
// Regex for IPV6
const pattern1 = /((([0-9a-fA-F]){1,4})\:){7}([0-9a-fA-F]){1,4}/g;
// Iterating over string to extract all IPV6 patterns
while ((match = pattern1.exec(subject)) !== null) {
console.log(match[0]);
}
OutputAvailable IP Addresses in the Given String Are:
257.120.223.13
fffe:3465:efab:23fe:2235:6565:aaab:0001
Time Complexity: O(n)
Space Complexity: O(1)
Similar Reads
Extracting all present dates in any given String using Regular Expressions Given a string Str, the task is to extract all the present dates from the string. Dates can be in the format i.e., mentioned below: DD-MM-YYYYYYYY-MM-DDDD Month YYYY Examples: Input: Str = "The First Version was released on 12-07-2008.The next Release will come on 12 July 2009. The due date for paym
6 min read
Validate LEI(Legal Entity Identifier) using Regular Expression Given some Legal Entity Identifier, the task is to check whether they are valid using regular expressions. Rules for the valid LEI are: LEI code length is comprised of a 20-digit alphanumeric code.The first four characters are digits. Next two places are reserved for digit Zero.Next 12 characters ar
6 min read
Validate Corporate Identification Number (CIN) using Regular Expression Given some Corporate Identification Number, the task is to check if they are valid or not using regular expressions. Rules for the valid CIN are: CIN is a 21 digits alpha-numeric code.It starts with either alphabet letter U or L.Next five characters are reserved for digits (0-9).Next two places are
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
Validate Phone Numbers ( with Country Code extension) using Regular Expression Given some Phone Numbers, the task is to check if they are valid or not using regular expressions. Rules for the valid phone numbers are: The numbers should start with a plus sign ( + )It should be followed by Country code and National number.It may contain white spaces or a hyphen ( - ).the length
5 min read
Validating UPI IDs using Regular Expressions Given some UPI IDs, the task is to check if they are valid or not using regular expressions. Rules for the valid UPI ID: UPI ID is an alphanumeric String i.e., formed using digits(0-9), alphabets (A-Z and a-z), and other special characters.It must contain '@'.It should not contain whitespace.It may
5 min read