VOOZH about

URL: https://www.geeksforgeeks.org/projects/extracting-ip-address-from-a-given-string-using-regular-expressions/

⇱ Extracting IP Address From a Given String Using Regular Expressions - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Extracting IP Address From a Given String Using Regular Expressions

Last Updated : 23 Jul, 2025

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:

  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:


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)

Comment