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

时间:2016-07-08 07:53:00

标签: c# .net regex

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

2 个答案:

答案 0 :(得分:4)

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

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

    return rg.IsMatch(ipAddressFromList);
}

答案 1 :(得分:0)

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

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);
}
相关问题