问题
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