vb.net IP (v4) 地址的正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13386461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regex for IP (v4) address
提问by StealthRT
I am trying to use regex for the IP address from an HTML page:
我正在尝试对 HTML 页面中的 IP 地址使用正则表达式:
<html>
<head><title>Current IP Check</title></head>
<body>Current IP Address: xx.xxx.xxx.xx</body>
</html>
And my VB.Net code is currently this:
我的 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
However, the end results are nothing for IP.
然而,最终结果对 IP 来说毫无意义。
I'm just looking to get xx.xxx.xxx.xx
我只是想得到xx.xxx.xxx.xx
What would I be doing incorrectly?
我会做错什么?
回答by Neolisk
Regular expression for an IP address is much more complex than you outlined. But there is no reason to re-invent the wheel. Please have a look at Regular Expression Examples, here is the one that accounts for everything:
IP 地址的正则表达式比您概述的要复杂得多。但是没有理由重新发明轮子。请看一看正则表达式示例,这里是说明所有内容的示例:
\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
回答by Paul S.
IPv4s don't have + or - signs, if you're not in danger of other similar string patterns you can actually do it even more simply
IPv4 没有 + 或 - 符号,如果您没有其他类似字符串模式的危险,您实际上可以更简单地做到这一点
\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b
Furthermore if you need to find IPv6 addresses then you could try something like
此外,如果您需要查找 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
Note that both of these will find "candidates", and shouldn't be used for validation. If you want to validate IPv6 with RegEx, look here.
请注意,这两个都将找到“候选人”,不应用于验证。如果您想使用 RegEx 验证 IPv6,请查看此处。
回答by Steve
For such simple html you could just use strings.split:
对于这么简单的 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()
回答by shA.t
As @Neolisk's answer is worked in most of the time, I edit it to accept number with leading zero:
由于@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
To accept some IPs like 000010.10.10.000001
接受一些 IP,例如 000010.10.10.000001

