正则笔记

来源:互联网 发布:我对人工智能的看法 编辑:程序博客网 时间:2024/05/21 10:23
public class Test {public static void main(String[] args) throws Exception{test();//splitDemo();//getMails();//getNetMails();//ipSort();}public static void checkTel(){String str = "13900001111";String reg = "1[358]\\d{9}";System.out.println(str.matches(reg));}public static void checkQQ(){String str = "23456";String reg = "[1-9][0-9]{4,14}";boolean flag = str.matches(reg);if(flag)System.out.println(str+"...is ok");elseSystem.out.println(str+"...is err");}public static void splitDemo(){String str = "zhangsan.lisi.wangwu";String reg = "\\.";String[] arr = str.split(reg);System.out.println(arr.length);for(String s : arr){System.out.println(s);}}public static void test(){String str = "erkktyqqqquizzzzzoo";//将叠词替换//str=str.replaceAll("(.)\\1+", "*");str=str.replaceAll("(.)\\1+", "$1");System.out.println(str);}public static void test_1(){String str = "ming tian jiu yao fang jia le ,da jia. ";String reg = "[a-z]{3}";//将规则封装成对象Pattern p = Pattern.compile(reg);//让正则对象和要作用的字符串相关联。获取匹配器对象。Matcher m = p.matcher(str);//m.find();//如这儿执行,接下来继续循环执行,则指针指向第二个.min则不显示while(m.find()){System.out.println(m.group());}}public static void test_2(){String str = "我我...我我我...我要...我要要...学学...学学学..编编..程程程程..程....程程";str=str.replaceAll("\\.+", "");//去掉.。  .代表任意 \.代表. ,加上转义\\.,+代表不止一个.。全部替换为空System.out.println(str);str=str.replaceAll("(.)\\1+", "$1");//(.)代表组。组内第一个为任意,$1为替换提取之前的第一个组。System.out.println(str);}public static void ipSort(){String str = "192.68.1.254 102.49.23.013 10.10.10.10 2.2.2.2 8.108.80.20";str=str.replaceAll("(\\d+)", "00$1");System.out.println(str);str=str.replaceAll("0*(\\d{3})", "$1");System.out.println(str);String[] arrIP=str.split(" ");//Arrays.sort(arrIP);TreeSet<String> ts = new TreeSet<String>();System.out.println("++++++++++++++++++++++++++++");for(String s:arrIP){ts.add(s);}for(String s:ts){System.out.println(s+"||"+s.replaceAll("0*(\\d+)", "$1"));}}public static void getMails() throws Exception{BufferedReader bufr = new BufferedReader(new FileReader("mail.txt"));String line = null;// "[a-zA-Z0-9_]+@[a-zA-Z0-9]+(\\.[a-zA-Z]+)+" 较为精确匹配正则String mailreg = "\\w+@\\w+(\\.\\w+)+"; //相对不太精确Pattern p = Pattern.compile(mailreg);while((line=bufr.readLine())!=null){Matcher m = p.matcher(line);while(m.find()){System.out.println(m.group());}}}public static void getNetMails() throws Exception{System.out.println("开始");URL url = new URL("http://www.xxx.com.cn/Jobs.asp");URLConnection conn = url.openConnection();BufferedReader bufIn = new BufferedReader(new InputStreamReader(conn.getInputStream()));String line = null;String mailreg = "\\w+@\\w+(\\.\\w+)+";Pattern p = Pattern.compile(mailreg);while((line=bufIn.readLine())!=null){Matcher m = p.matcher(line);while(m.find()){System.out.println(m.group());}}System.out.println("结束");}}