Reputation: 590
I have a list named IpAddressList
with some IP addresses like 192.168.0.5 and so on.
The user can search the list for a given IP address, also by using the wildcard *
This is my method:
public bool IpAddressMatchUserInput(String userInput, String ipAddressFromList)
{
Regex regex = new Regex("");
Match match = regex.Match(ipAddressFromList);
return match.Success;
}
The userInput
can be for example:
In all cases the method should return true, but I don't know how to use Regex in combination with the userInput
and how the regex should look.
Upvotes: 1
Views: 1096
Reputation: 176169
Here's a more robust version that does not break if the user input contains Regex metacharacters such as \
, or unmatched parenthesis:
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);
}
Upvotes: 0
Reputation: 30022
I think this should work (covering also 192.*.0.*
):
public static bool IpAddressMatchUserInput(String userInput, String ipAddressFromList)
{
Regex rg = new Regex(userInput.Replace("*", @"\d{1,3}").Replace(".", @"\."));
return rg.IsMatch(ipAddressFromList);
}
Upvotes: 4