正则匹配ip

基本思路就是要每个点之间的元素为整数,最多为3位整数[0-9]\{1,3\},然后用 . 拼接起来,加上^和$更精确的限制匹配对象

[root@ilovelluvia re]# cat ip.txt

qazzdd

1.1.1.1

2.2.2.2

3.3.3.3

0.0.0.0

[root@ilovelluvia re]# grep “[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}” ip.txt

1.1.1.1

2.2.2.2

3.3.3.3

0.0.0.0

[root@ilovelluvia re]# grep “^[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}$” ip.txt

1.1.1.1

2.2.2.2

3.3.3.3

0.0.0.0

这里精度不够,需要严格限制整数为1-255(第一个元素不能为0,后面的可以为0),即0-9 10-99 100-199 200-249 250-255

 

[root@ilovelluvia re]# grep ‘^\([1-9]\|[1-9][0-9]\|1[0-9][0-9]\|2[0-4][0-9]\|25[0-5]\)\.\([0-9]\|[1-9][0-9]\|1[0-9][0-9]\|2[0-4][0-9]\|25[0-5]\)\.\([0-9]\|[1-9][0-9]\|1[0-9][0-9]\|2[0-4][0-9]\|25[0-5]\)\.\([0-9]\|[1-9][0-9]\|1[0-9][0-9]\|2[0-4][0-9]\|25[0-5]\)$’ ip.txt

1.1.1.1

2.2.2.2

3.3.3.3

或者

[root@ilovelluvia re]# grep ‘^\([1-9]\|[1-9][0-9]\|1[0-9][0-9]\|2[0-4][0-9]\|25[0-5]\)\(\.\([0-9]\|([1-9][0-9]\|1[0-9][0-9]\|2[0-4][0-9]\|25[0-5]\)\)\{3\}$’ ip.txt

1.1.1.1

2.2.2.2

3.3.3.3

正则匹配ip
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Scroll to top
0
Would love your thoughts, please comment.x
()
x