700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Java使用正则表达式从字符串中提取 IP 地址

Java使用正则表达式从字符串中提取 IP 地址

时间:2022-02-28 00:06:47

相关推荐

Java使用正则表达式从字符串中提取 IP 地址

import java.util.regex.Matcher;import java.util.regex.Pattern;public class ExtractIP {public static void main(String[] args) {String ipString = "1.1.1.1 2.2.2.2";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 = pile(IPADDRESS_PATTERN);Matcher matcher = pattern.matcher(ipString);while (matcher.find()) {System.out.println(matcher.group());}}}

/*** This class provides a variety of basic utility methods that are not* dependent on any other classes within the org.jamwiki package structure.*/public class Utilities {private static Pattern VALID_IPV4_PATTERN = null;private static Pattern VALID_IPV6_PATTERN = null;private static final String ipv4Pattern = "(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])";private static final String ipv6Pattern = "([0-9a-f]{1,4}:){7}([0-9a-f]){1,4}";static {try {VALID_IPV4_PATTERN = pile(ipv4Pattern, Pattern.CASE_INSENSITIVE);VALID_IPV6_PATTERN = pile(ipv6Pattern, Pattern.CASE_INSENSITIVE);} catch (PatternSyntaxException e) {//logger.severe("Unable to compile pattern", e);}}/*** Determine if the given string is a valid IPv4 or IPv6 address. This method* uses pattern matching to see if the given string could be a valid IP address.** @param ipAddress A string that is to be examined to verify whether or not* it could be a valid IP address.* @return <code>true</code> if the string is a value that is a valid IP address,* <code>false</code> otherwise.*/public static boolean isIpAddress(String ipAddress) {Matcher m1 = Utilities.VALID_IPV4_PATTERN.matcher(ipAddress);if (m1.matches()) {return true;}Matcher m2 = Utilities.VALID_IPV6_PATTERN.matcher(ipAddress);return m2.matches();}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。