免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
12
最近访问板块 发新帖
楼主: jakee304
打印 上一主题 下一主题

如何使用正则表达式匹配IP地址? [复制链接]

论坛徽章:
0
11 [报告]
发表于 2007-09-13 17:19 |只看该作者
我也是和烈火兄的方法一样

论坛徽章:
0
12 [报告]
发表于 2008-01-06 19:47 |只看该作者
下面这个表达式是正确的

  1. egrep '^([1-9][0-9]?|1[0-9]{2}|2[0-2][0-9]|23[0-2])(\.(1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){3}$'  filename
复制代码


使用regex来控制数字的大小,感觉真是麻烦,呵呵

[ 本帖最后由 ubuntun 于 2008-1-6 19:50 编辑 ]

论坛徽章:
0
13 [报告]
发表于 2008-09-02 15:08 |只看该作者
都够长的啊呵呵

论坛徽章:
0
14 [报告]
发表于 2008-09-06 00:53 |只看该作者
Now that we have a subexpression to match a single number from 0 through 255, we can wrap it in parentheses and insert it in place of each \d{1,3} in the earlier regex. This gives us (broken across lines to fit the width of the page):

    ^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.
        ([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$



Quite a mouthful! Was it worth the trouble? You have to decide for yourself based upon your own needs. It matches only syntactically correct IP addresses, but it can still match semantically incorrect ones, such as 0.0.0.0 (invalid because all the digits are zero). With lookahead (☞133), you can disallow that specific case by putting (?!0+\.0+\.0+\.0+$) after ^, but at some point, you have to decide when being too specific causes the cost/benefit ratio to suffer from diminishing returns. Sometimes it's better to take some of the work out of the regex. For example, if you go back to ^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$ and wrap each component in parentheses to stuff the numbers into the program's version of $1, $2, $3, and $4, you can then validate them by other programming constructs.


参考:Mastering.Regular.Expressions.3rd.Edition.Aug.2006.chm 5.2节

论坛徽章:
0
15 [报告]
发表于 2015-05-13 12:11 |只看该作者
"([0-9]{1,3}\.){3}[0-9]{1,3}" 即可

论坛徽章:
1
IT运维版块每日发帖之星
日期:2015-10-12 06:20:00
16 [报告]
发表于 2015-05-14 14:02 |只看该作者
ifconfig  eth0 | sed -n '2p' | awk -F':' '{print $2}' | awk '{print $1}'
拿去
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP