一隻檢查 IP 和 Hostname 格式的 JAVA 小程式
還是那句老話,我不喜歡JAVA。那這篇文章怎麼會存在呢?因為要解決同事開發Android軟體上所遇到的問題,所以不得不跳下來寫。
import java.util.regex.*; public class CheckIPHostName { public static void main(String[] args) { String input; if (args.length > 0) { input = args[0]; } else { // No input was given. Print a message and exit. System.out.println("Usage: java DateClient <server_host_name>"); return; } Pattern IpPattern = Pattern.compile( "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3} ([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$" ); Pattern HostPattern = Pattern.compile( "^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)* ([A-Za-z]|[A-Za-z][A-Za-z0-9\\-]*[A-Za-z0-9])$" ); Matcher matcherIp = IpPattern.matcher( input ); Matcher matcherHost = HostPattern.matcher( input ); if( matcherIp.matches() ) { System.out.printf( "%s is an IP address.\n", input ); } else if( matcherHost.matches() ) { System.out.printf( "%s is a host name.\n", input ); } else { System.out.printf( "%s is invalid.\n", input ); } return; } }
留言
張貼留言