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

标签 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 结合使用以及正则表达式的外观。

最佳答案

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

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

    return rg.IsMatch(ipAddressFromList);
}

关于c# - 正则表达式:使用通配符根据用户输入检查 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38261556/

相关文章:

c# - asmx Soap Web 服务中的额外类(class)

c# - 如何将 DataGridViewComboBoxCell 转换为 DataGridViewTextBoxCell

c# - 在 .NET 中的事务期间插入之前获取新 ID

c# - UnitTest 一种依赖于时间的方法

javascript - 重复输入vb.net

C# 命名空间指南

c# - 多语言 wpf 应用程序

regex - 将字符串解析为哈希

r - 如何在 R 中使用 stringr 检测 ¹?

JavaScript 正则表达式替换为字母数字,仅在字符组之间添加空格