function IP2V(ip) { re=/(\d+)\.(\d+)\.(\d+)\.(\d+)/g //匹配IP地址的正则表达式 if(re.test(ip)) { return RegExp.$1*Math.pow(255,3))+RegExp.$2*Math.pow(255,2))+RegExp.$3*255+RegExp.$4*1 } else { throw new Error("不是一个正确的IP地址!") } }
(?<Num1>\d+)\.(?<Num2>\d+)\.(?<Num3>\d+)\.(?<Num4>\d+$)Regex regex = new Regex(@"(?<Num1>\d+)\.(?<Num2>\d+)\.(?<Num3>\d+)\.(?<Num4>\d+$)"); Match m = regex.Match("192.168.1.58"); string[] gn = regex.GetGroupNames(); if(m.Success) { MessageBox.Show(m.Groups["Num1"].Value); } 你可以看看正则表达式中各个符号的意思。 在这里你查看gn你就知道了。
Regex regex = new Regex(@"(?<Num1>\d+)\.(?<Num2>\d+)\.(?<Num3>\d+)\.(?<Num4>\d+$)"); Match m = regex.Match("192.168.1.58"); string[] gn = regex.GetGroupNames(); if(m.Success) { // check num1 ---num4 whether between 0 to 255 if(Convert.ToInt32(m.Groups["Num1"].Value) <0 || Convert.ToInt32(m.Groups["Num1"].Value) >255 ...) { return false; } }
直接用.分成数组,判断每个元素>=0 且<= 255就可。
{
re=/(\d+)\.(\d+)\.(\d+)\.(\d+)/g //匹配IP地址的正则表达式
if(re.test(ip))
{
return RegExp.$1*Math.pow(255,3))+RegExp.$2*Math.pow(255,2))+RegExp.$3*255+RegExp.$4*1
}
else
{
throw new Error("不是一个正确的IP地址!")
}
}
Match m = regex.Match("192.168.1.58");
string[] gn = regex.GetGroupNames();
if(m.Success) {
MessageBox.Show(m.Groups["Num1"].Value);
}
你可以看看正则表达式中各个符号的意思。 在这里你查看gn你就知道了。
Match m = regex.Match("192.168.1.58");
string[] gn = regex.GetGroupNames();
if(m.Success) {
// check num1 ---num4 whether between 0 to 255
if(Convert.ToInt32(m.Groups["Num1"].Value) <0 || Convert.ToInt32(m.Groups["Num1"].Value) >255 ...) {
return false;
}
}