无法在JavaScript中匹配IP正则表达式

Unable to match IP regex in JavaScript

本文关键字:IP 正则表达式 JavaScript      更新时间:2023-09-26

以下是我的代码,我试图在前端验证IP地址,但不知何故,这个Regex不起作用-

var patt = /[0-255]'.[0-255]'.[0-255]'.[0-255]/;
var str = "90.89.99.90";
if(str.match(patt))
  console.log("Valid IP");
else
  console.log("Invalid IP");

它应该输出-有效IP

而这类IP应该返回-无效IP

"fd.45.67.90"、"256.67.67.89"、"@@.45.67.9"等

让我知道我用regex做错了什么。

Regex范围不会按照您的想法执行操作。[x-y]范围包含从xy的所有ascii字符。

因此,[0-255]匹配从02的字符(也称为012)和5,或者简称为[0125]


要匹配从0255的数字,可以执行以下操作:

'd'd?|1'd'd|2([0-4]'d|5[0-5])

想法:

  • 'd'd?-一位或两位数字
  • 1'd'd-从100199的数字
  • 2[0-4]'d——从200249的数字
  • 25[0-5]-从250255的数字

要匹配整个IP,您可以执行以下操作:

^(('d'd?|1'd'd|2([0-4]'d|5[0-5]))'.){3}('d'd?|1'd'd|2([0-4]'d|5[0-5]))$

[...]表示一个"字符类",这意味着它列出了应该匹配的字符;它匹配您列出的任何一个字符。因此,您的正则表达式正在检查每个段是否有一个单个字符,它是0、1、2或5中的任何一个(0-2给我们0、1和2;然后5给我们5,第二个5被忽略)。它应该检查数字('d)和其中1-3个({1,3}):

var patt = /'d{1,3}'.'d{1,3}'.'d{1,3}'.'d{1,3}/;

您可能还需要^(输入开始)和$(输入结束),这样foo123.123.123.123bar就不匹配:

var patt = /^'d{1,3}'.'d{1,3}'.'d{1,3}'.'d{1,3}/$;

当然,这还不足以检查IP是否有效。它只是检查是否有预期的数字;它会很高兴地称CCD_ 31有效。

如果你想正确验证它(例如,数字在有效范围内,过滤掉无效的段组合等),你可以提取这个全面的URL验证正则表达式的IP部分(因为URL可以包含IP地址,所以它涵盖了这一点)。值得庆幸的是,Diego和其他作者对它进行了很好的评论,清楚地确定了哪些比特可以做什么:

//
// Regular Expression for URL validation
//
// Author: Diego Perini
// Updated: 2010/12/05
// License: MIT
//
// Copyright (c) 2010-2013 Diego Perini (http://www.iport.it)
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
// the regular expression composed & commented
// could be easily tweaked for RFC compliance,
// it was expressly modified to fit & satisfy
// these test for an URL shortener:
//
//   http://mathiasbynens.be/demo/url-regex
//
// Notes on possible differences from a standard/generic validation:
//
// - utf-8 char class take in consideration the full Unicode range
// - TLDs have been made mandatory so single names like "localhost" fails
// - protocols have been restricted to ftp, http and https only as requested
//
// Changes:
//
// - IP address dotted notation validation, range: 1.0.0.0 - 223.255.255.255
//   first and last IP address of each class is considered invalid
//   (since they are broadcast/network addresses)
//
// - Added exclusion of private, reserved and/or local networks ranges
//
// - Made starting path slash optional (http://example.com?foo=bar)
//
// - Allow a dot (.) at the end of hostnames (http://example.com.)
//
// Compressed one-line versions:
//
// Javascript version
//
// /^(?:(?:https?|ftp):'/'/)(?:'S+(?::'S*)?@)?(?:(?!(?:10|127)(?:'.'d{1,3}){3})(?!(?:169'.254|192'.168)(?:'.'d{1,3}){2})(?!172'.(?:1[6-9]|2'd|3[0-1])(?:'.'d{1,3}){2})(?:[1-9]'d?|1'd'd|2[01]'d|22[0-3])(?:'.(?:1?'d{1,2}|2[0-4]'d|25[0-5])){2}(?:'.(?:[1-9]'d?|1'd'd|2[0-4]'d|25[0-4]))|(?:(?:[a-z'u00a1-'uffff0-9]-*)*[a-z'u00a1-'uffff0-9]+)(?:'.(?:[a-z'u00a1-'uffff0-9]-*)*[a-z'u00a1-'uffff0-9]+)*(?:'.(?:[a-z'u00a1-'uffff]{2,}))'.?)(?::'d{2,5})?(?:[/?#]'S*)?$/i
//
// PHP version
//
// _^(?:(?:https?|ftp)://)(?:'S+(?::'S*)?@)?(?:(?!(?:10|127)(?:'.'d{1,3}){3})(?!(?:169'.254|192'.168)(?:'.'d{1,3}){2})(?!172'.(?:1[6-9]|2'd|3[0-1])(?:'.'d{1,3}){2})(?:[1-9]'d?|1'd'd|2[01]'d|22[0-3])(?:'.(?:1?'d{1,2}|2[0-4]'d|25[0-5])){2}(?:'.(?:[1-9]'d?|1'd'd|2[0-4]'d|25[0-4]))|(?:(?:[a-z'x{00a1}-'x{ffff}0-9]-*)*[a-z'x{00a1}-'x{ffff}0-9]+)(?:'.(?:[a-z'x{00a1}-'x{ffff}0-9]-*)*[a-z'x{00a1}-'x{ffff}0-9]+)*(?:'.(?:[a-z'x{00a1}-'x{ffff}]{2,}))'.?)(?::'d{2,5})?(?:[/?#]'S*)?$_iuS
//
var re_weburl = new RegExp(
  "^" +
    // protocol identifier
    "(?:(?:https?|ftp)://)" +
    // user:pass authentication
    "(?:''S+(?::''S*)?@)?" +
    "(?:" +
      // IP address exclusion
      // private & local networks
      "(?!(?:10|127)(?:''.''d{1,3}){3})" +
      "(?!(?:169''.254|192''.168)(?:''.''d{1,3}){2})" +
      "(?!172''.(?:1[6-9]|2''d|3[0-1])(?:''.''d{1,3}){2})" +
      // IP address dotted notation octets
      // excludes loopback network 0.0.0.0
      // excludes reserved space >= 224.0.0.0
      // excludes network & broacast addresses
      // (first & last IP address of each class)
      "(?:[1-9]''d?|1''d''d|2[01]''d|22[0-3])" +
      "(?:''.(?:1?''d{1,2}|2[0-4]''d|25[0-5])){2}" +
      "(?:''.(?:[1-9]''d?|1''d''d|2[0-4]''d|25[0-4]))" +
    "|" +
      // host name
      "(?:(?:[a-z''u00a1-''uffff0-9]-*)*[a-z''u00a1-''uffff0-9]+)" +
      // domain name
      "(?:''.(?:[a-z''u00a1-''uffff0-9]-*)*[a-z''u00a1-''uffff0-9]+)*" +
      // TLD identifier
      "(?:''.(?:[a-z''u00a1-''uffff]{2,}))" +
      // TLD may end with dot
      "''.?" +
    ")" +
    // port number
    "(?::''d{2,5})?" +
    // resource path
    "(?:[/?#]''S*)?" +
  "$", "i"
);

这里有一个正则表达式变体(基于上面ndn的答案),它将检查整个输入文本是否是有效的IP:

^(?:(?:'d{1,2}|1'd{2}|2(?:[0-4]'d|5[0-5]))'.){3}(?:'d{1,2}|1'd{2}|2(?:[0-4]'d|5[0-5]))$

参见regex演示

以下是一个可用于从较大文本中提取有效IP的解决方案:

'b(?:(?:'d{1,2}|1'd{2}|2(?:[0-4]'d|5[0-5]))'.){3}(?:'d{1,2}|1'd{2}|2(?:[0-4]'d|5[0-5]))'b

查看另一个演示

解释

  • ^-字符串的开头(如果只需要在字符串的开头不匹配,则替换为'b单词边界)
  • (?:(?:'d{1,2}|1'd{2}|2(?:[0-4]'d|5[0-5]))'.){3}-出现3次
    • (?:'d{1,2}|1'd{2}|2(?:[0-4]'d|5[0-5]))-1或2位序列,或1xx数字(1'd{2})或200-255范围内的整数范围(得益于2(?:[0-4]'d|5[0-5])
    • '.-文字周期
  • (?:'d{1,2}|1'd{2}|2(?:[0-4]'d|5[0-5]))-见上文(仅为IP地址的最后一部分)
  • $-字符串结尾(如果您只需要一个完整的单词匹配,请替换为'b

注意:在JS中,您可以使用文字表示法来声明这些regexp,例如:

/'b(?:(?:'d{1,2}|1'd{2}|2(?:[0-4]'d|5[0-5]))'.){3}(?:'d{1,2}|1'd{2}|2(?:[0-4]'d|5[0-5]))'b/g
/^(?:(?:'d{1,2}|1'd{2}|2(?:[0-4]'d|5[0-5]))'.){3}(?:'d{1,2}|1'd{2}|2(?:[0-4]'d|5[0-5]))$/