Regular expression for IP Address Validation
我想验证该值是否为有效的IP地址….!
我曾经验证过
1 | ValidIpAddressRegex ="^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"; |
它工作得很好,但是当我给出像
有一个简单的方法。您只需要拆分
此外,您还可以在用于IPv6的
只是因为我觉得很有趣:
1 | ^(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))$ |
这里有一个应该处理ips(v4)的regex。
找一个IPv4,结果我自己创建了它。(这只处理常见的点状变量,即0.0.0.0-255.255.255.255)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | ^ # START OF STRING (?=\d+\.\d+\.\d+\.\d+$) # Lookahead, require this format: number.number.number.number END OF STRING (?: # Start non-capture group (number 0-255 + optional dot) (?: # Start non-capture group (number 0-255) 25[0-5] # 250-255 | # OR 2[0-4][0-9] # 200-249 | # OR 1[0-9]{2} # 100-199 | # OR [1-9][0-9] # 10-99 | # OR [0-9] # 0-9 ) # End non-capture group \.? # Optional dot (enforced in correct positions by lookahead) ){4} # End non-capture group (number + optional dot), repeat 4 times $ # END OF STRING |
无评论:
1 | ^(?=\d+\.\d+\.\d+\.\d+$)(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.?){4}$ |
一些测试代码:
1 2 3 4 5 6 7 8 9 10 11 | function isValidIpv4Addr(ip) { return /^(?=\d+\.\d+\.\d+\.\d+$)(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.?){4}$/.test(ip); } var testAddr = ['192.68.35.35','0.0.0.0','255.0.0.0','192.168.1.0','192.168.0.1','255.255.255.0','1.1.1.1','255.255.255.255','249.249.249.249','200.200.200.200','199.199.199.199','100.100.100.100','99.99.99.99','0.0.0.0','9.9.9.9','10.10.10.10','99.99.99.99','100.100.100.100','109.109.109.109','110.110.110.110','199.199.199.199','200.200.200.200','249.249.249.249','250.250.250.250','255.255.255.255','256.256.256.260','192.168.0.0/24','192.168..1','192.168.1','1','1.','1.1','1.1.','1.1.1','1.1.1.','1.1.1.1.','1.1.1.1.1','.1.1.1.1','01.01.01.01','09.09.09.09','1.0.0.1.0','010.1.1.1','123456','123123123123','.127.0.0.1']; for (var i = 0; i < testAddr.length; i++) { document.getElementById('ipv4tests').innerHTML += ' <li> ' + testAddr[i] + ' ' + (isValidIpv4Addr(testAddr[i]) ? '<font color="green">VALID!</font>' : '<font color="red">INVALID!</font>') + ' </li> '; } |
1 2 | <ul id="ipv4tests"> </ul> |
这对所有可能的情况都适用。
1 | ^(([1-9]?\d|1\d\d|2[0-5][0-5]|2[0-4]\d)\.){3}([1-9]?\d|1\d\d|2[0-5][0-5]|2[0-4]\d)$ |
我知道这是旧的,但是试试这个:
1 | /^(?:(?:2[0-4]\d|25[0-5]|1\d{2}|[1-9]?\d)\.){3}(?:2[0-4]\d|25[0-5]|1\d{2}|[1-9]?\d)(?:\:(?:\d|[1-9]\d{1,3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5]))?$/ |
今天我为一个PHP函数做了这个。
它处理0.0.0.0到255.255.255.255之间的IP,以及0到65535之间的端口。
实例:
1 2 3 4 5 6 7 8 | validates: 0.0.0.0:0 255.0.0.0 192.168.1.0:8080 does not validate: 192.168.0.0/24 192.168..1 192.168.1 |
我知道这是一个弗兰肯瑞格,但它仍然有效!
如果端口不重要,请使用此端口:
1 | /^(?:(?:2[0-4]\d|25[0-5]|1\d{2}|[1-9]?\d)\.){3}(?:2[0-4]\d|25[0-5]|1\d{2}|[1-9]?\d)$/ |
试试这个简短的:
1 | ^(([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])(\.(?!$)|(?=$))){4}$ |
下面是这个regex的测试用例:
1 2 3 4 5 6 7 8 9 | function verifyIp(ip) { return /^(([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])(\.(?!$)|(?=$))){4}$/.test(ip||""); } ["192.68.35.35","0.0.0.0","255.0.0.0","192.168.1.0","192.168.0.1","255.255.255.0","1.1.1.1","255.255.255.255","249.249.249.249","200.200.200.200","199.199.199.199","100.100.100.100","99.99.99.99","0.0.0.0","9.9.9.9","10.10.10.10","99.99.99.99","100.100.100.100","109.109.109.109","110.110.110.110","199.199.199.199","200.200.200.200","249.249.249.249","250.250.250.250","255.255.255.255","256.256.256.260","192.168.0.0/24","192.168..1","192.168.1","1","1.","1.1","1.1.","1.1.1","1.1.1.","1.1.1.1.","1.1.1.1.1",".1.1.1.1","01.01.01.01","09.09.09.09","1.0.0.1.0","010.1.1.1","123456","123123123123",".127.0.0.1"].forEach(function(item){ is_valid = verifyIp(item); $(''+item+' <span class="'+(is_valid?'correct':'wrong')+'">'+(is_valid?'VALID':'INVALID')+'</span>').appendTo('#result'); }); |
1 2 3 4 5 6 7 8 9 10 | .item { font-weight: bold; } .wrong { color: red; } .correct { color: green; } |
1 | <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> |
以下是解决方案:
1 | ^(([01]?[0-9]?[0-9]|2([0-4][0-9]|5[0-5]))\.){3}([01]?[0-9]?[0-9]|2([0-4][0-9]|5[0-5]))$ |
您也可以尝试以下操作:
1 | ^((?:(?:^|\.)(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])){4})$ |
我们希望模式重复四次-在这种情况下,我们的模式是一个0-255范围内的数字,前面是句点
请参阅此regex 101演示以获得完整的解释。
您可以简单地使用这个regex来验证没有端口号的任何IP地址,比如这种格式(192.168.1.1)
1 | /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/ |
只是扩展了@davidfaber的优秀解决方案。要匹配IPv4"点分十进制"表示法(无范围/端口):
1 | ^(((1?[1-9]?|10|2[0-4])\d|25[0-5])($|\.(?!$))){4}$ |
匹配示例:https://regex101.com/r/vx2hk4/15
编码高尔夫有人吗?
这个前妻工作得很好,但相信我这是一个过分的杀伤力。要进行条件比较(如小于255),最好使用regex和条件值的组合。
1 | ^(([0-1]?[0-9]?[0-9]{1})|(2?[0-4]?[0-9]{1})|(25[0-5]))\.(([0-1]?[0-9]?[0-9]{1})|(2?[0-4]?[0-9]{1})|(25[0-5]))\.(([0-1]?[0-9]?[0-9]{1})|(2?[0-4]?[0-9]{1})|(25[0-5]))\.(([0-1]?[0-9]?[0-9]{1})|(2?[0-4]?[0-9]{1})|(25[0-5]))$ |
试图缩短Grealy的版本
1 | ^((1?\d?\d|2[0-4]\d|25[0-5])($|\.(?!$))){4}$ |
注意:与以前的版本一样,它不能正确处理八进制数,如0177.0.0.1。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | Choose if you want to enter a single ip or range of ip's <select [(ngModel)]="ipranging"> <option selected disabled value="none"> -- select an option -- </option> <option value='ip'>Single Ip address</option> <option value="range">Ip range</option> </select> <form *ngIf="ipranging === 'ip'" novalidate [formGroup]="testForm1" class="render"> <label>IP Address: <input formControlName="inp" placeholder='0.0.0.0'/></label> <input formControlName="inp3" hidden/> <!-- <p *ngIf="testForm.controls.inp.status == 'INVALID' && testForm.controls.inp.value != ''">Invalid </p> <p *ngIf="testForm.controls.inp2.status == 'INVALID' && testForm.controls.inp2.value != ''">Invalid </p> --> <p *ngIf="testForm1.controls.inp.value != '' && testForm1.controls.inp.status == 'INVALID'">Invalid </p> </form> <form *ngIf="ipranging === 'range'" novalidate [formGroup]="testForm2" class="render"> <label>Starting IP: <input formControlName="inp" placeholder='0.0.0.0'/></label> <label> Ending IP: <input formControlName="inp2" placeholder='0.0.0.0'/></label> <input formControlName="inp3" hidden/> <!-- <p *ngIf="testForm.controls.inp.status == 'INVALID' && testForm.controls.inp.value != ''">Invalid </p> <p *ngIf="testForm.controls.inp2.status == 'INVALID' && testForm.controls.inp2.value != ''">Invalid </p> --> <p *ngIf="testForm2.controls.inp.value != '' && testForm2.controls.inp.status == 'INVALID' || testForm2.controls.inp2.value != '' && testForm2.controls.inp2.status == 'INVALID'">Invalid </p> <p *ngIf="testForm2.controls.inp3.errors.value2GreaterThanValue1 == true">Starting IP is larger than the ending IP </p> </form> |
您也可以检查我的给定表达式,我已经检查并编写了一个程序在Java中验证IPv4地址。如果IPv4地址正确,则返回true,反之亦然。
字符串模式="^([01]?D?| 2[0-4]d 25[0-5]).([01]?D?| 2[0-4]d 25[0-5]).([01]?D?| 2[0-4]d 25[0-5]).([01]?D?| 2[0-4]d 25[0-5])美元"
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.Scanner; class Solution{ public static void main(String []args){ Scanner in = new Scanner(System.in); while(in.hasNext()){ String IP = in.next(); System.out.println(IP.matches(new MyRegex().pattern)); } } } class MyRegex{ String pattern="^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\dCongrats, you solved this challenge!\\d?|2[0-4]\\d|25[0-5])$"; } |
科林·赫伯特指出了最好的解决办法。但是没有人通过为它提供代码来"解释",所以这里说("只是因为我觉得这很有趣:";)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | var aIP = [ '192.168.0.1', '255.255.255.255', '1.2.34.647', '256.0.0.0', '255,0,0,0', '123.123.123', '1.2.3.4.5' ]; aIP.forEach(function(ipAddr) { var a = ipAddr.split('.'), cnt = 4; document.write('Testing ' + ipAddr + '<br/>'); try { a.forEach(function(v) { if( v<0 || v>255 ) throw false; cnt--; }); if( cnt!=0 ) throw false; cnt--; document.write('- Pass!<br/>'); } catch (e) { document.write('- Fail!<br/>'); } }); |
也试试这个:
1 | (((?<![\d])([0-9][\.])|(?<![\d])([1-9][0-9][\.])|(?<![\d])(1[0-9]{2}[\.])|(?<![\d])(2[0-5][0-5][\.]))(([0-9][\.])|([1-9][0-9][\.])|(1[0-9]{2}[\.])|(2[0-5][0-5][\.])){2}(([0-9])(?![\d])|([1-9][0-9])(?![\d])|(1[0-9]{2})(?![\d])|(2[0-5][0-5])(?![\d]))) |
虽然这是一个5年前的问题,所以我怀疑你还在寻找答案。
在另一个线程上发布了更多信息:使用regexp验证IPv4地址
为模式例如192.168.23.28/255.255.255.0
1 | ^(25[0-5]|2[0-4][0-9]|[01]?[1-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-4]|2[0-4][0-9]|[01]?[1-9][0-9]?)\/(((128|192|224|240|248|252|254)\.0\.0\.0)|(255\.(0|128|192|224|240|248|252|254)\.0\.0)|(255\.255\.(0|128|192|224|240|248|252|254)\.0)|(255\.255\.255\.(0|128|192|224|240|248|252|254)))$ |
为模式例如192.168.26.82/24或192.168.23.28/255.255.255.0
1 | ^(25[0-5]|2[0-4][0-9]|[01]?[1-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-4]|2[0-4][0-9]|[01]?[1-9][0-9]?)\/([1-9]|1[0-9]|2[0-9]|3[0-2]|(((128|192|224|240|248|252|254)\.0\.0\.0)|(255\.(0|128|192|224|240|248|252|254)\.0\.0)|(255\.255\.(0|128|192|224|240|248|252|254)\.0)|(255\.255\.255\.(0|128|192|224|240|248|252|254))))$ |
为模式例192.168.26.28
1 | ^(25[0-5]|2[0-4][0-9]|[01]?[1-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-4]|2[0-4][0-9]|[01]?[1-9][0-9]?)$ |
对于网络掩码例如255.255.255.0
1 | ^(((128|192|224|240|248|252|254)\.0\.0\.0)|(255\.(0|128|192|224|240|248|252|254)\.0\.0)|(255\.255\.(0|128|192|224|240|248|252|254)\.0)|(255\.255\.255\.(0|128|192|224|240|248|252|254)))$ |
OP要求验证IP地址。q的措词几乎可以肯定地表示ipv4(而不是ipv6)。我已经在操作上评论了有效性检查可能会走多远,并为一个响应者采取非重新方法而鼓掌。由于我还想(在某些情况下)测试地址的有效性,如果我在公共服务器上使用它,我想出了以下JS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | function isSimpleIPv4( ip, u=true ) { if ((ip === undefined) || (ip === null) || (ip.length > 15)) return false; var p = ip.split(\'.\'); if (p.length != 4) return false; p.forEach( function(v,k){p[k]=Number(v);} ); if (isNaN(p[0]) || isNaN(p[1]) || isNaN(p[2]) || isNaN(p[3]) ) return false; if ((p[0] < 1) || (p[0] > 255) || (p[1] < 0) || (p[1] > 255) || (p[2] < 0) || (p[2] > 255) || (p[3] < 0) || (p[3] > 255)) return false; if (!u) return true; if ((p[0] > 223)) return 'multicast'; if ((p[0] == 127)) return 'loopback'; if ((p[0] == 10)) return 'RFC1918'; if ((p[0] == 192) && (p[1] == 168)) return 'RFC1918'; if ((p[0] == 172) && (p[1] >= 16) && (p[1] <= 31)) return 'RFC1918'; return true; } |
如果要检查"有用"地址,则只需要字符串IP;否则,如果只检查0-255.0-255.0-255.0-255.0-255,则使用IP字符串调用函数,并返回false。在前一种情况下,函数将返回真/假/什么时候是有用性的"失败"原因。rfc1918网站访问者想要访问的地址将无法从公共服务器上访问,甚至可能危及自己的一个服务器(可能是环回范围127.x.x.x中的地址)。同样,使用多播地址也没有帮助。如果你对有用性检查感兴趣,但不关心原因,那么你只需要做
IPv4有4个从0到255的数字块,可能在左侧包含填充零。每个块用一个点隔开。
简单简短的IPv4验证程序:
1 2 | var block"([0-1]{0,1}[0-9]{1,2}|2[0-4][0-9]|25[0-5]|)"; var ipv4 ="(" + block +"\\.){3}" + block ; |
验证任何IP,如:
- 0.0.12
- 121.23 4.12
- 23.45.1256
- 03.045.012056
- 03.45.126
- 0.45.122.255
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | import { Component } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'], }) export class AppComponent { ipranging=""; testForm1: FormGroup; testForm2: FormGroup; constructor(private fb: FormBuilder){ } ngOnInit(): void { const ipPattern = "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"; this.testForm1 = this.fb.group({ inp: ['', Validators.pattern(ipPattern)], inp3: ['', Validators.pattern(ipPattern)] }); this.testForm2 = this.fb.group({ inp: ['', Validators.pattern(ipPattern)], inp2: ['', Validators.pattern(ipPattern)], inp3: ['', Validators.pattern(ipPattern)] }); this.testForm2.setValidators(this.comparisionValidator); } public comparisionValidator(group: FormGroup) : any{ const control1 = group.controls['inp']; const control2 = group.controls['inp2']; var control1array = control1.value.split('.'); var control2array = control2.value.split('.'); if(parseInt(control1array[0]) > parseInt(control2array[0]) ){ group.controls['inp3'].setErrors({ 'value2GreaterThanValue1': true }); console.log(group); } else if(parseInt(control1array[1]) > parseInt(control2array[1]) ){ group.controls['inp3'].setErrors({ 'value2GreaterThanValue1': true }); console.log(group); } else if(parseInt(control1array[2]) > parseInt(control2array[2]) ){ group.controls['inp3'].setErrors({ 'value2GreaterThanValue1': true }); console.log(group); } else if(parseInt(control1array[3]) > parseInt(control2array[3]) ){ group.controls['inp3'].setErrors({ 'value2GreaterThanValue1': true }); console.log(group); } else { group.controls['inp3'].setErrors({ 'value2GreaterThanValue1': false }); console.log(group); } } } |
试试这个,
1 | ValidIpAddressRegex ="^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$" |
这应该管用
1 | ^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$ |