【问题标题】:C# Regex extract (ip + whitespace + port) in long string长字符串中的 C# 正则表达式提取(ip + 空格 + 端口)
【发布时间】:2018-07-18 14:07:05
【问题描述】:

我在使用 C# 中的正则表达式来提取 IP + 端口 时遇到问题,格式为 X.X.X.X Port,位于长字符串的中间。

字符串示例:

"C:/programs/CamClient/ver/0.0.1.202/client.exe" "12345" "RemoteClient.exe" "/path" "118.118.118.118 5978 AInRy+Nj9CVVaE6iCN1hSQ== 106937037""-UseNewX3DFramebuffers=0" "-ClientPort=55000" "-AuthToken=hC-dlUy2rLe7CUQDtk2LOQ"

我需要提取“118.118.118.118 5978”作为新字符串 IP总是外部的,端口总是在5000-5999之间,更准确

我的实际正则表达式不工作,我已经尝试解决并最终迷失在正则表达式世界的中间。

        Regex regex = new Regex(@"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}[\s]\d{1,4}$");

        String testString = "asdaasd32 as333 /remote 'ID93494' 118.118.118.118 5978 AInRy+Nj9CVVaE6iCN1hSQ=='106937037'";

        MatchCollection matches = regex.Matches(testString);
        foreach (MatchCollection match in matches)
        {
            Console.WriteLine(match.ToString());
        }

如果有人知道我做错了什么,将不胜感激。

【问题讨论】:

    标签: regex ip port


    【解决方案1】:

    您需要从您的正则表达式中删除开始的 ^ 和结束的 $:

    \d{1,3}(\.\d{1,3}){3} +\d{4}
    

    Demo

    【讨论】:

      【解决方案2】:

      请检查此正则表达式。

      (?:(?:2[0-5][0-5]|1\d\d|[1-9]\d|\d)\.){3}(?:2[0-5][0-5]|1\d\d|[1-9]\d|\d)\s(5\d{3})
      

      【讨论】:

      • 这个最佳答案,因为这个匹配IP地址有效(0-255)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-21
      • 2013-10-07
      • 2017-11-18
      相关资源
      最近更新 更多