Movatterモバイル変換


[0]ホーム

URL:


Open In App

Let us see how to extract IP addresses from a file using Python.
 

Algorithm :  

r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
  • For every element of the list search for the pattern using the search() function, store the IP addresses in a list.
  • Display the list containing the IP addresses.


The file to be processed is test.txt : 
 

test.txt


 

python3
# importing the moduleimportre# opening and reading the filewithopen('C:/Users/user/Desktop/New Text Document.txt')asfh:fstring=fh.readlines()# declaring the regex pattern for IP addressespattern=re.compile(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})')# initializing the list objectlst=[]# extracting the IP addressesforlineinfstring:lst.append(pattern.search(line)[0])# displaying the extracted IP addressesprint(lst)

Output :

The above Python program displays any kind of IP addresses present in the file. We can also display thevalid IP addresses.

Rules for a valid IP Address : 

  • The numbers should be in a range of 0-255
  • It should consist of 4 cells separated by '.'


The regular expression for valid IP addresses is :
 

((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)


 

Explanation of Regular Expression used for valid IP:

Since we cannot use 0-255 range in regular expression we divide the same in 3 groups:

  • 25[0-5] - represents numbers from 250 to 255
  • 2[0-4][0-9] - represents numbers from 200 to 249
  • [01]?[0-9][0-9]?- represents numbers from 0 to 199


The file to be processed is test2.txt : 
 

test2.txt 


 

python3
# importing the moduleimportre# opening and reading the filewithopen('test2.txt')asfh:string=fh.readlines()# declaring the regex pattern for IP addressespattern=re.compile('''((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)''')# initializing the list objectsvalid=[]invalid=[]# extracting the IP addressesforlineinstring:line=line.rstrip()result=pattern.search(line)# valid IP addressesifresult:valid.append(line)# invalid IP addresseselse:invalid.append(line)# displaying the IP addressesprint("Valid IPs")print(valid)print("Invalid IPs")print(invalid)

Output :


Improve

Explore

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

[8]ページ先頭

©2009-2025 Movatter.jp