# 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.13fffe:3465:efab:23fe:2235:6565:aaab:0001`

Create a regex pattern to validate the number as written below:

1. 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])â€œ
2. 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 ` `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 it(` `             ``subject.begin(), subject.end(), pattern);` `         ``it != regex_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 it(` `             ``subject.begin(), subject.end(), pattern1);` `         ``it != regex_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]);` `}`

Output

```Available 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)