Java 从字符串中提取IP地址:实战指南
要从字符串中提取IP地址,您可以使用正则表达式来匹配IP地址模式。下面是一个使用Java的示例代码:\n\njava\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class IPAddressExtractor {\n public static void main(String[] args) {\n String str = "jdbc:dm://localhost:5236";\n String ipAddress = extractIPAddress(str);\n System.out.println(ipAddress);\n }\n\n public static String extractIPAddress(String str) {\n String ipAddress = "";\n String pattern = "\b(?:\d{1,3}\.){3}\d{1,3}\b";\n Pattern regexPattern = Pattern.compile(pattern);\n Matcher matcher = regexPattern.matcher(str);\n if (matcher.find()) {\n ipAddress = matcher.group();\n }\n return ipAddress;\n }\n}\n
\n\n这个示例中,我们使用了正则表达式模式\b(?:\d{1,3}\.){3}\d{1,3}\b
来匹配IP地址的模式。extractIPAddress
方法接收一个字符串参数,然后使用Pattern
和Matcher
类来找到匹配的IP地址部分。最后,它返回提取到的IP地址。\n\n在这个示例中,输出将是localhost
,因为localhost
在jdbc:dm://localhost:5236
中被视为IP地址的一部分。如果您想仅提取IP地址而不包括主机名,您可以根据您的需求修改正则表达式模式。
原文地址: http://www.cveoy.top/t/topic/p8LX 著作权归作者所有。请勿转载和采集!