VOOZH about

URL: https://www.geeksforgeeks.org/perl/perl-extracting-ip-address-from-a-string-using-regex/

โ‡ฑ Perl | Extract IP Address from a String using Regex - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Perl | Extract IP Address from a String using Regex

Last Updated : 26 Sep, 2019
Perl stands for Practical Extraction and Reporting Language and this not authorized acronym. One of the most powerful features of the Perl programming language is Regular Expression and in this article, you will learn how to extract an IP address from a string. A regular expression can be either simple or complex, depending on the pattern you want to match like our title - Extracting IP Address from a String using Regex. Extracting IP address from a string can be a simple or challenging task. Hence, people love and hate regular expressions. They are a great way to express a simple pattern and a horrific way to express complicated ones. Some of the examples of Quantifiers as well as Characters and their meaning is given below:
Quantifier Meaning
a* zero or more a's
a+ one or more a's
a? zero or one a's
a{m} exactly m a's
a{m,} at least m a's
a{m,n} at least m but at most n a's
Character Meaning
^ beginning of string
$ end of string
. any character except newline
* match 0 or more times
+ match 1 or more times
? match 0 or 1 times
| alternative
( ) grouping
[ ] set of characters
{ } repetition modifier
\ quote or special

Extracting an IP Address from a String

The easiest way is just to take any string of four decimal numbers separated by periods is
\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/ OR /^\d+\.\d+\.\d+\.\d+$/
In the following example we simply extracting an IP address from a given string. Output: ๐Ÿ‘ Image
But, the above example also accepts the wrong IP address like 596.368.258.269. We know, a proper decimal dotted IP address has no value larger than 255 and writing a regex that matches the integers 0 to 255 is hard work as the regular expressions donโ€™t understand arithmetic; they operate purely textually. Therefore, you have to describe the integers 0 through 255 in purely textual means. Now, we will see an implementation of extracting an IP address which will check octet range also. Output: ๐Ÿ‘ Image
If you change the string to
[my $ip = "MY IP ADDRESS IS 127.36.59.63 THIS IS A VALID IP ADDRESS";] 
then the output is ๐Ÿ‘ Image
In the following example, we are accepting a string from the user which contains an IP address and then we are extracting the IP address from it. We used the chomp() function to remove any newline character from the end of a string. Output: ๐Ÿ‘ Image
Comment
Article Tags:
Article Tags:

Explore