使用正则表达式从字符串中提取IP地址 [英] Extract ip addresses from Strings using regex

查看:1768
本文介绍了使用正则表达式从字符串中提取IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在应用程序中,我获取包含IP地址的字符串,但这些字符串没有精确的格式。
我们所知道的是这些字符串可能包含一个IP地址。

In an application, I get strings containing IP Addresses but these string have no precise format. All we know is that these strings may contain an IP address.

这里是字符串的示例:


  • XPSPort

  • IP_10.29.167.187

  • 10.29。 166.193

我想获得一个Java代码,如果有一个或者返回,它将提取字符串的ip地址如果字符串不包含IP地址。

I would like to get a Java code that extracts the ip address of the string if there is one or that returns "" if the string doesn't contain an ip address.

我尝试了这段代码,但它不起作用:

I tried this code but it doesn't work :

String IPADDRESS_PATTERN = 
        "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
        "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
        "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
        "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";

Pattern pattern = Pattern.compile(IPADDRESS_PATTERN);
Matcher matcher = pattern.matcher(ipString);
        if (matcher.find()) {
            return matcher.group();
        }
        else{
            return "0.0.0.0";
        }

我很确定使用RegExp是实现这一目标的最佳途径,但我这些不是很好,所以有人能帮我找到好的RegExp吗?

I'm pretty sure using RegExp is the best way to achieve that but I'm not very good with these so can someone help me find the good RegExp?

提前致谢。

推荐答案

理查德的链接帮助我找到答案。
这是工作代码:

Richard's link helped me find the answer. here's the working code :

String IPADDRESS_PATTERN = 
        "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";

Pattern pattern = Pattern.compile(IPADDRESS_PATTERN);
Matcher matcher = pattern.matcher(ipString);
if (matcher.find()) {
    return matcher.group();
} else{
    return "0.0.0.0";
}

这篇关于使用正则表达式从字符串中提取IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆