我正在尝试使用正则表达式从HTML页面获取IP地址:
<html>
<head><title>Current IP Check</title></head>
<body>Current IP Address: xx.xxx.xxx.xx</body>
</html>
我的VB.Net代码目前是这样的:
Using wClient As New WebClient
ip = wClient.DownloadString("http://checkip.dyndns.org/")
ip = Regex.Match(ip, "^[+-]?(\d+(\.\d+)?|\.\d+)$", RegexOptions.Singleline).ToString
End Using
然而,最终结果对IP来说无关紧要。
我只想获得 xx.xxx.xxx.xx
我会做错什么?
答案 0 :(得分:7)
IP地址的正则表达式比您概述的要复杂得多。但没有理由重新发明轮子。请查看Regular Expression Examples,以下是解释所有问题的内容:
\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]?)\.(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]?)\b
答案 1 :(得分:0)
IPv4没有+或 - 符号,如果您没有其他类似字符串模式的危险,您实际上可以更简单地执行此操作
\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b
此外,如果您需要查找IPv6地址,那么您可以尝试类似
的内容\b(?:[\dA-F]{1,4}:){1,7}(?:(?::[\dA-F]{1,4}){1,6}|(?:::[\dA-F]{1,4}){1,7}|:|[\dA-F]{1,4})?\b
请注意,这两个都会找到“候选人”,不应该用于验证。 如果要使用RegEx验证IPv6,请查看here。
答案 2 :(得分:0)
对于这样简单的html,你可以使用strings.split:
Dim source As String = wClient.DownloadString("http://checkip.dyndns.org/")
Dim ip As String = Split(Split(source, "Current IP Address:")(1), "</body>")(0).Trim()
答案 3 :(得分:0)
由于@ Neolisk的答案在大多数时间都有效,我编辑它以接受前导零的数字:
\b(0*(25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(0*(25[0-5]|2[0-4]\d|[01]?\d\d?))\b
接受某些IP,例如000010.10.10.000001