如何将变量与IPv4正则表达式正确匹配 [英] How to correctly match a variable against an IPv4 regex
问题描述
我是JavaScript的新手,正在尝试创建一个简单的函数来检查变量是否为有效的IPv4地址.
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.
我从stackexchange复制了正则表达式,并试图将其与硬编码变量匹配,但是在线编辑器声称它是无效的JavaScript代码.
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');
}
如何正确检查静态变量是否是带有正则表达式的有效IPv4地址?
How do I correctly check if a static variable is a valid IPv4 address with a regex?
推荐答案
您必须使用定界符将正则表达式括起来:
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}$/)) {
这篇关于如何将变量与IPv4正则表达式正确匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!