【问题标题】:Regex: Check IP address against user input with wildcard正则表达式:使用通配符检查用户输入的 IP 地址
【发布时间】:2016-07-08 07:52:59
【问题描述】:

我有一个名为 IpAddressList 的列表,其中包含一些 IP 地址,例如 192.168.0.5 等。

用户可以在列表中搜索给定的 IP 地址,也可以使用通配符 *

这是我的方法:

public bool IpAddressMatchUserInput(String userInput, String ipAddressFromList)
{
    Regex regex = new Regex("");

    Match match = regex.Match(ipAddressFromList);

    return match.Success;
}

userInput 可以是例如:

  • 192.168.0.*
  • 192.
  • 192.168.0.5
  • 192.*.0.*

在所有情况下,该方法都应返回 true,但我不知道如何将正则表达式与 userInput 结合使用以及正则表达式的外观。

【问题讨论】:

  • 这是一个有效的输入 192.*.0.* 吗?
  • @user3185569 是的 :)
  • 检查下面的答案。
  • IP 地址列表字符串中的分隔符是什么?
  • 该方法在foreach循环中为每个IP地址调用(参数:ipAddressFromList)

标签: c# .net regex


【解决方案1】:

我认为这应该可行(还包括192.*.0.*):

public static bool IpAddressMatchUserInput(String userInput, String ipAddressFromList)
{
    Regex rg = new Regex(userInput.Replace("*", @"\d{1,3}").Replace(".", @"\."));

    return rg.IsMatch(ipAddressFromList);
}

【讨论】:

  • 他可能也应该用\. 替换. 以逃避它并按字面意思对待它。
  • @user3185569 测试,工作,干得好,谢谢:)
  • 这是一个错误答案,因为"[0-255]" 匹配零、一、二或五。
  • 小心,[0-255] 与 0 到 255 的数字范围不匹配!
  • 匹配单个字符,“0”、“1”、“2”或“5”。 '1' 被匹配,因为它包含在字符类的字符范围 '0-2' 中
【解决方案2】:

如果用户输入包含诸如\ 之类的正则表达式元字符或不匹配的括号,这是一个更强大的版本,它不会中断:

public static bool IpAddressMatchUserInput(string userInput, string ipAddressFromList)
{
    // escape the user input. If user input contains e.g. an unescaped 
    // single backslash we might get an ArgumentException when not escaping
    var escapedInput = Regex.Escape(userInput);

    // replace the wildcard '*' with a regex pattern matching 1 to 3 digits
    var inputWithWildcardsReplaced = escapedInput.Replace("\\*", @"\d{1,3}");

    // require the user input to match at the beginning of the provided IP address
    var pattern = new Regex("^" + inputWithWildcardsReplaced);

    return pattern.IsMatch(ipAddressFromList);
}

【讨论】:

    猜你喜欢
    • 2011-03-01
    • 2011-08-27
    • 2011-05-26
    • 1970-01-01
    • 2013-01-08
    • 2016-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多