繁体   English   中英

从字符串中剥离IPv6和端口号

[英]Stripping IPv6 and port number from a string

我有一个正则表达式来检查字符串是否包含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);
}

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

然后,要消除重复项,可以使用不允许它们的HashSet<string>

为了添加“简单”一行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");
}

您可以使用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#演示

请注意,如果要限制正则表达式模式仅匹配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")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM