【问题标题】:Stripping IPv6 and port number from a string从字符串中剥离 IPv6 和端口号
【发布时间】:2019-04-08 16:29:24
【问题描述】:

我有一个正则表达式来检查字符串是否包含 IP 地址。

我有没有检查并删除任何端口号/ipv6 详细信息 - 所以我只剩下 IP 地址:

117.89.65.117.ipv6.la 应该变成 117.89.65.117
121.58.242.206:449 应该变成 121.58.242.206

这是我目前想出的代码来检查 - 谁能帮我修改它以去除上面的额外信息?

private void AddToList(String IP)
{
    Regex ipAddress = new Regex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b");
    Match result = ipAddress.Match(IP);
    if (chkQuotes.Checked) IP = "\"" + IP + "\"";
    if (result.Success)
        if (cIPlist.IndexOf(IP) <= 0)
            cIPlist.Add(IP);
}

【问题讨论】:

  • 你的输入是什么样的?像 117.89.65.117.ipv6.la 或 121.58.242.206:449 一样作为整个字符串?
  • 看来你可以使用if (chkQuotes.Checked) IP = $"\"{result.Value}\"";。但是在检查if (result.Success)之后再做。
  • 如果你添加 parentesis 你可以访问第 1 组中想要的信息
  • @DragandDrop 为什么要在这里添加捕获组?我认为 OP 只需要通过访问 result.Value 来获得整场比赛

标签: c# regex vb.net


【解决方案1】:

您可以使用result.Value 访问整个匹配值,而不是重复使用IP 变量。

此外,在方法中使用正则表达式之前定义正则表达式以加快速度是一个好主意。

private static HashSet<string> cIPlist = new HashSet<string>();
private static readonly Regex ipAddress = new Regex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b");

private void AddToList(String IP)
{
    var result = ipAddress.Match(IP);
    if (result.Success)                 # Check if there is a match
    {
        if (chkQuotes.Checked)          # If the checkbox is checked
        {
            IP = $"\"{result.Value}\""; # Add quotes around the match value
        }
        cIPlist.Add(IP);                # Add to hashset of strings
    }
}

请参阅C# demo。

请注意,如果您想将正则表达式模式限制为仅匹配 IP 而不是像 999.999.999.999 这样的字符串,您可以使用来自 regular-expressions.info 的众所周知的模式:

new Regex(@"\b(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}\b")

【讨论】:

    【解决方案2】:

    首先我们可以使用https://www.regular-expressions.info/ip.html 修复正则表达式并减少一点。与(){3}。

    然后要消除重复,您可以使用不允许它们的HashSet&lt;string&gt;。

    为了添加“简单”的一行 linQ 并进行测试,我将 AddToList 参数切换为 params string[]。

    static HashSet<string> resultingList = new HashSet<string>();
    static string pattern = @"(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9]";
    static Regex ipRegex = new Regex(pattern);
    
    static void AddToList(params string[] ips) =>
        resultingList.UnionWith(
            ips.Select(x => ipRegex.Match(x))
                .Where(x => x.Success)
                .Select(x => x.Value)
        );
    
    private static void TestMethod()
    {
        var inputs = new[]{
            "123.123.123.13:256",
            "123.123.123.13:256", //duplicate line
            "17.89.65.117.ipv6.la ",
            "21.58.242.206:449",
            "666.666.666.666"
        };
    
        AddToList(inputs);
        AddToList("127.0.0.1");
    }
    

    【讨论】:

      猜你喜欢
      • 2010-09-19
      • 2012-09-30
      • 2020-11-15
      • 2018-04-20
      • 2017-11-28
      • 1970-01-01
      • 2015-03-12
      • 1970-01-01
      • 2011-06-18
      相关资源
      最近更新 更多