正则表达式:使用通配符根据用户输入检查 IP 地址

本文关键字:输入 用户 检查 IP 地址 通配符 正则表达式 | 更新日期: 2023-09-27 17:56:09

我有一个名为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结合使用以及正则表达式的外观。

正则表达式:使用通配符根据用户输入检查 IP 地址

我认为这应该有效(也涵盖192.*.0.*):

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

这是一个更健壮的版本,如果用户输入包含正则表达式元字符(如 ' 或不匹配的括号),它不会中断:

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);
}