javascript正则表达式检查IP地址 [英] javascript regular expression to check for IP addresses
问题描述
我有几个IP地址,如:
I have several ip addresses like:
-
115.42.150.37
-
115.42.150.38
-
115.42.150.50
115.42.150.37
115.42.150.38
115.42.150.50
如果我想搜索所有3个ip地址,我应该写什么类型的正则表达式?例如,如果我 115.42.150。*
(我将能够搜索所有3个IP地址)
What type of regular expression should I write if I want to search for the all the 3 ip addresses? Eg, if I do 115.42.150.*
(I will be able to search for all 3 ip addresses)
我现在可以做的是: / [0-9] {1-3} \。[0-9] {1-3} \。[0-9] {1 -3} \。[0-9] {1-3} /
但它似乎无法正常工作。
What I can do now is something like: /[0-9]{1-3}\.[0-9]{1-3}\.[0-9]{1-3}\.[0-9]{1-3}/
but it can't seems to work well.
谢谢。
推荐答案
你已经有的正则表达式有几个问题:
The regex you've got already has several problems:
首先,它包含点。在正则表达式中,点表示匹配任何字符,您只需匹配实际点。为此,你需要逃避它,所以在点前放一个反斜杠。
Firstly, it contains dots. In regex, a dot means "match any character", where you need to match just an actual dot. For this, you need to escape it, so put a back-slash in front of the dots.
其次,但你匹配每个部分的任何三位数。这意味着您将匹配0到999之间的任何数字,这显然包含许多无效的IP地址编号。
Secondly, but you're matching any three digits in each section. This means you'll match any number between 0 and 999, which obviously contains a lot of invalid IP address numbers.
这可以通过使数字匹配更复杂来解决;在这个网站上有其他答案解释如何做到这一点,但坦率地说,这是不值得的 - 在我看来,你最好用点分割字符串,然后只是将四个块验证为数字整数范围 - 即:
This can be solved by making the number matching more complex; there are other answers on this site which explain how to do that, but frankly it's not worth the effort -- in my opinion, you'd be much better off splitting the string by the dots, and then just validating the four blocks as numeric integer ranges -- ie:
if(block > 0 && block <256) {....}
希望有所帮助。
这篇关于javascript正则表达式检查IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!