【发布时间】:2016-04-19 18:01:04
【问题描述】:
我一直在尝试将以下内容从 Python 转换为 node.js。这是一个使用正则表达式检查 IP 地址是公共还是私有的简单程序:
import re
def is_private_ip(ip):
"""
Returns `True` if the `ip` parameter is a private network address.
"""
c = re.compile('(^127\.0\.0\.1)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^192\.168\.)')
if c.match(ip): return True
return False
print is_private_ip('192.168.0.1') # True
print is_private_ip('8.8.8.8') # False
print is_private_ip('109.231.231.221') # False
我是这样用 Javascript 实现的:
var localIp = new RegExp(/(^127\.0\.0\.1)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^192\.168\.)/);
console.log('192.168.0.1'.match(localIp));
console.log('8.8.8.8'.match(localIp));
console.log('109.231.231.221'.match(localIp));
这给了我以下输出:
[ '192.168.',
undefined,
undefined,
undefined,
undefined,
undefined,
'192.168.',
index: 0,
input: '192.168.0.1' ]
null
null
在我看来它似乎有效(甚至不确定)。应该公开的两个 IP 返回null,所以我猜这是对的。我不明白另一场比赛的输出吗?一直没弄明白是什么意思
【问题讨论】:
-
.match() 为您提供字符串中可能的匹配数。也许您正在寻找的是 .test() 方法。
标签: javascript regex node.js