java_正則表示式的3個例子
阿新 • • 發佈:2018-11-09
package cn.itcast.regextest.demo; import java.util.HashSet; public class TestDemo { public static void main(String[] args) { // test1(); // test2(); test3(); } public static void test3() { /** * 郵箱地址校驗 * * */ String mail="[email protected]"; boolean b=mail.matches("[a-zA-Z_]+\\@[a-zA-Z_]+\\.([a-zA-Z]{1,3})+"); System.out.println(mail+":"+b); } public static void test2() { /** * ip地址切割:ip=192.168.1.0 3.5.6.4 168.16.7.64 * * */ // 1、對ip進行補0; String ip="192.168.1.0 3.5.6.4 168.16.7.64"; ip=ip.replaceAll("(\\d+)", "00$1"); // 3、保留後三位 ip=ip.replaceAll("0*(\\d{3})", "$1"); // 3、把每個ip切割出來; String[] ips=ip.split(" +"); HashSet<String>hs=new HashSet<String>(); for(String ipp:ips) { hs.add(ipp); } for(String jpp:hs) { // 4、去掉多餘的零 jpp=jpp.replaceAll("0*(\\d+)", "$1"); System.out.println(jpp); } } public static void test1() { String str="我我....我我..我我...我要..要要..要.要要.要回回...回回..回回....回回..回回..回回家...家家...家家...家家.家"; str=str.replaceAll("\\.", ""); str=str.replaceAll("(.)\\1+", "$1"); System.out.println(str); } }