Regex to match Ipv4 with mask

家住魔仙堡 提交于 2021-02-04 21:17:30

问题


I am validating a Ipv4 address by a regex and it does not support subnet mask.

^([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])$

Can some one help me with the regex which supports mask as well.

Here is a working example of this regex: demo


回答1:


Add (?:/[0-2]\d|/3[0-2])? at the end of your regex. You can also simplify the regex:

^([01]?\d\d?|2[0-4]\d|25[0-5])(?:\.(?:[01]?\d\d?|2[0-4]\d|25[0-5])){3}(?:/[0-2]\d|/3[0-2])?$



回答2:


In your example, if you want it to match both adresses, remove beginning ^ and trailing $



来源:https://stackoverflow.com/questions/30590193/regex-to-match-ipv4-with-mask

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!