Javascript 什么';我的IP地址正则表达式有什么问题?
我正在尝试检查字符串是否为有效的IP地址:Javascript 什么';我的IP地址正则表达式有什么问题?,javascript,regex,Javascript,Regex,我正在尝试检查字符串是否为有效的IP地址: export function checkIpIsValid(ip) { const regex = new RegExp("^([1-2]?[0-9]{1,2}\.){3}[1-2]?[0-9]{1,2}$") return regex.test(ip);
export function checkIpIsValid(ip) {
const regex = new RegExp("^([1-2]?[0-9]{1,2}\.){3}[1-2]?[0-9]{1,2}$")
return regex.test(ip);
}
但此测试失败,因为它返回true:
expect(checkIpIsValid("1.1.1.1")).toBe(true);
expect(checkIpIsValid("152.154.22.35")).toBe(true);
expect(checkIpIsValid("552.154.22.35")).toBe(false);
// These three are fine
// But the one below is not, it doesn't contain 4 parts so it should return false. Instead, it is returning true.
expect(checkIpIsValid("154.22.35")).toBe(false);
// Expected value to be (using ===):
// false
// Received:
// true
问题是,当我检查它时,它在这种情况下运行良好…不要使用new RegExp()
。这需要字符串输入,但您的表达式不会因字符串而转义。你只是用双引号把它括起来,这是行不通的
function checkIpIsValid(ip) {
return /^(?:\d{1,3}\.){3}\d{1,3}$/.test(ip);
}
checkIpIsValid('123.12.12'); // returns false
checkIpIsValid('123.12.12.12'); // returns true
使用正则表达式文字:
function checkIpIsValid(ip) {
const regex = /^([1-2]?[0-9]{1,2}\.){3}[1-2]?[0-9]{1,2}$/;
return regex.test(ip);
}
或者恰当地避开他的表情:
function checkIpIsValid(ip) {
const regex = new RegExp("^([1-2]?[0-9]{1,2}\\.){3}[1-2]?[0-9]{1,2}$");
return regex.test(ip);
}
JS具有正则表达式文本,这正是因为它避免了双重转义的需要。仅对动态生成的表达式使用
new RegExp()
,而不对固定表达式使用。No,这不匹配。正则表达式对于IPs不正确,但与输入不匹配。比较一下。你能描述一下你想要匹配什么吗?@tomalak Yep,在regex101.com中,这似乎是正确的,但是当你运行javascript时,我得到了一个与完全相同的正则表达式的匹配。嗯,问题是其中一个将匹配我的第三个测试用例:552.154.22.35
,它不应该匹配