我的IP地址正则表达式出了什么问题?

时间:2017-12-03 10:26:43

标签: 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);                                                    
}   

但是这个测试失败了,因为它返回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

问题是,当我在https://regex101.com/上查看它时,它就可以正常运行......

2 个答案:

答案 0 :(得分:3)

请勿使用ModuleNotFoundError: No module named 'Bio'。这需要字符串输入,但您的表达式不会转义为字符串。你只是用双引号将其括起来,但这不起作用。

使用正则表达式文字:

new RegExp()

或正确地逃避表达:

function checkIpIsValid(ip) {
    const regex = /^([1-2]?[0-9]{1,2}\.){3}[1-2]?[0-9]{1,2}$/;    
    return regex.test(ip);                                                    
}

JS具有正则表达式文字正是因为它避免了双重转义的需要。仅将function checkIpIsValid(ip) { const regex = new RegExp("^([1-2]?[0-9]{1,2}\\.){3}[1-2]?[0-9]{1,2}$"); return regex.test(ip); } 用于动态构建的表达式,而不是固定表达式。

答案 1 :(得分:1)

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