python regular expression matching IP address

First, the experimental environment

1.Windows 7x64

2.python2.7

Second, the purpose of the experiment

Gets the text string from the text, the legitimate IP address filtering

2.1 text reads as follows

Please enter a valid IP address, IP address, and other illegal characters will be filtered! 
Add, delete, change the IP address, save and close Notepad! 
192.168.8.84 
192.168.8.85 
192.168.8.86 
0.0.0.1 
256.1.1.1 
192.256.256.256 
192.255.255.255 
aa.bb.cc.dd

2.2 Write a function to read a text file, filtering legitimate IP address

    def get_ip_list(self):
        try:
            file = open(self.smart_ip_list_file, 'r')
            str = file.readlines()
            str_del_enter = [x.strip('\n') for x in str]                                                            #去除\n
            comp = re.compile(r'^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}')
            str_legal_ip = [x for x in str_del_enter if comp.match(x)]                                              #筛选合法IP地址
            file.close()
            return str_legal_ip
        except:
            self.ui.textEdit.setText('读取"%s"报错' %(self.smart_ip_list_file))
            return []  

Code Description: 

1. Read all lines from a text file, are \ n addition to the end of the first line, the following code for removing \ n

str_del_enter = [x.strip('\n') for x in str]

2.IP address length is 32 bits (a total of 2 ^ 32 IP addresses), divided into four sections, each section 8, is represented by decimal numbers, each number ranging from 0 to 255, between paragraphs with a period apart  

The rules: each piece of the same, in the range of 0 to 255
0 to 255 corresponding to the regular expression (2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2}

  • 2 (5 [0-5] | [0-4] \ d) Matches: 200 to 255
  • ? [0-1] \ d {1,2} Match: 0 to 199

0-255 formula has been written out, then a total of four plus a middle point is very easy

  • Behind "point" and "digital" repeated three times on it, (\ ((2 (5 [0-5] |. [0-4] \ d)) | [0-1] \ d {1,2? })) {3}
  • All together, ((2 (5 [0-5] | [0-4] \ d)) |? [0-1] \ d {1,2}) (\ ((2 (5 [0-. 5] | [0-4] \ d)) | [0-1] \ d {1,2})) {3}?

With the above string matches the regular expression, there is a problem

256.1.1.1 -> matches 56.1.1.1

 

Solution, is added as the foregoing expression ^ finally compile the function call, the parameters as follows

comp = re.compile(r'^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}')

  

  

Guess you like

Origin www.cnblogs.com/hester/p/11223948.html