使用JavaScript正则表达式检查有效的IP地址

There are times when an Internet Protocol (IP) address needs to be verified/validated.  What are examples of valid IP addresses?

有时需要验证/验证Internet协议(IP)地址。 有效IP地址的示例有哪些?

127.0.0.1

127.0.0.1

1.2.3.4

1.2.3.4

192.168.1.100

192.168.1.100

The pattern is that we have 4 integer values (from 0 to 255) separated by periods. Can we use a really simple regular expression (RegExp) like this?

模式是我们有4个由句点分隔的整数值(从0到255)。 我们可以使用这样一个非常简单的正则表达式(RegExp)吗?

var ipRE = new RegExp( '^\d+\.\d+\.\d+\.\d$' );

var ipRE = new RegExp('^ \ d + \。\ d + \。\ d + \。\ d $');

What does this RegExp mean, and how is it supposed to work?

RegExp是什么意思,它应该如何工作?

^ - This symbol matches the beginning of the string.

^ -此符号与字符串的开头匹配。

\d - This meta-character matches a single digit (i.e., 0 to 9).

\ d-此元字符与一位数字匹配(即0到9)。

+ - This symbol says to repeat the preceding pattern or symbol 1 or more times (i.e., 1 or more digits).

+ -此符号表示重复前面的模式或符号1次或多次(即1个或多个数字)。

\. - This sequence is needed to match a period.  Since a period has special meaning in a RegExp, we have to precede it with the backslash to indicate that we don't want the special meaning, we really want to match a period.

\。 -需要此序列以匹配周期。 由于一个正则表达式在RegExp中具有特殊含义,因此我们必须在其前面加上反斜杠以表示我们不希望具有特殊含义,因此我们确实想匹配一个周期。

$ - This symbol matches the end of the string.

$ -此符号与字符串的结尾匹配。

So, this RegExp will match a string containing 4 integer values, separated by periods.  How can we check it out to see if it satisfies our requirements?

因此,此RegExp将匹配包含4个整数值(由句点分隔)的字符串。 我们如何检查它是否满足我们的要求?



IP address validation



Address: 


  When we try this simple page, and enter the simplest of IP addresses, (i.e., "0.0.0.0"), and press the Tab key to have the validate() function execute, we will probably be surprised to see the alert dialog box say "invalid".  What?!?  How did we get this simple RegExp wrong? The answer is that we forgot that the escape character (i.e., the backslash) that is used to identify one of the RegExp meta-characters needs to be present when we create the RegExp. Huh?

当我们尝试这个简单的页面,并输入最简单的IP地址(即“ 0.0.0.0”),然后按Tab键以使

  Alright, if you have a trivial alert() string containing '\d', what gets displayed? A "d". In order to have the string being passed to the RegExp() constructor contain the text we want, we have to escape the backslash (i.e., '\\d'), for each and every backslash in the expression... (sigh).  So, what we really needed to do was to have the RegExp assignment in the code be:

好吧,如果您有一个包含'\ d'的琐碎的

var ipRE = new RegExp( '^\\d+\\.\\d+\\.\\d+\\.\\d+$' );

var ipRE = new RegExp('^ \\ d + \\。\\ d + \\。\\ d + \\。\\ d

你可能感兴趣的:(字符串,正则表达式,python,java,人工智能)