How to correctly match a variable against an IPv4 regex

牧云@^-^@ 提交于 2020-05-02 07:14:46

问题


I'm new to JavaScript and am trying to create a simple function checking whether a variable is a valid IPv4 address, or not.

Currently, I'm just trying the code with an online tool.

I copied the regex from stackexchange and tried to match it against a hardcoded variable, but the online editor claims it's invalid JavaScript code.

ip='127.0.0.1';

if (ip.match(^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$){
    alert('IPv4');
}
else{
    alert('no IPv4');
}

How do I correctly check if a static variable is a valid IPv4 address with a regex?


回答1:


You have to surround the regex with delimiter:

if (ip.match(/^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$/)){
//    here __^                                                                                                                                                     and here __^

You could use a quantifier to reduce the length of regex:

if (ip.match(/^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])(\.[01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]){3}$/)) {


来源:https://stackoverflow.com/questions/42677205/how-to-correctly-match-a-variable-against-an-ipv4-regex

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