獲取需要使用到正則的兩個對象:
使用的是用正則對象Pattern 和匹配器Matcher。
用法:
范例:
Pattern p = Pattern.compile("a*b"); Matcher m = p.matcher("aaaaab"); boolean b = m.matches();
步驟:
1,先將正則表達式編譯成正則對象。使用的是Pattern類一個靜態的方法。compile(regex);
2,讓正則對象和要操作的字符串相關聯,通過matcher方法完成,并返回匹配器對象。
3,通過匹配器對象的方法將正則模式作用到字符串上對字符串進行針對性的功能操作
需求:獲取由3個字母組成的單詞。
public static void getDemo(){ String str = "da jia zhu yi le,ming tian bu fang jia,xie xie!"; //想要獲取由3個字母組成的單詞。 //剛才的功能返回的都是一個結果,只有split返回的是數組,但是它是把規則作為分隔符,不會獲取符合規則的內容。 //這時我們要用到一些正則對象。 String reg = "http://b[a-z]{3}//b"; Pattern p = Pattern.compile(reg); Matcher m = p.matcher(str); while(m.find()) { System.out.println(m.start()+"...."+m.end()); System.out.println("sub:"+str.substring(m.start(),m.end())); System.out.println(m.group()); }// System.out.println(m.find());//將規則對字符串進行匹配查找。// System.out.println(m.find());//將規則對字符串進行匹配查找。// System.out.println(m.group());//在使用group方法之前,必須要先找,找到了才可以取。}
校驗郵件
public static void checkMail(){ String mail = "[email protected]"; mail = "[email protected]"; String reg = "[a-zA-Z_0-9]+@[a-zA-Z0-9]+(//.[a-zA-Z]+)+"; reg = "http://w+@//w+(//.//w+)+";//簡化的規則。籠統的匹配。 boolean b = mail.matches(reg); System.out.println(mail+":"+b);}
網絡爬蟲 (獲取郵箱)
class GetMailList {public static void main(String[] args) throws Exception{ String reg = "http://w+@[a-zA-Z]+(//.[a-zA-Z]+)+"; getMailsByWeb(reg);}public static void getMailsByWeb(String regex)throws Exception{ URL url = new URL("http://localhost:8080/myweb/mail.html"); URLConnection conn = url.openConnection(); BufferedReader bufIn = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; Pattern p = Pattern.compile(regex); while((line=bufIn.readLine())!=null) { //System.out.println(line); Matcher m = p.matcher(line); while(m.find()) { System.out.println(m.group()); } } bufIn.close();}public static void getMails(String regex)throws Exception{ BufferedReader bufr = new BufferedReader(new FileReader("mail.txt")); String line = null; Pattern p = Pattern.compile(regex); while((line=bufr.readLine())!=null) { //System.out.println(line); Matcher m = p.matcher(line); while(m.find()) { System.out.println(m.group()); } } bufr.close();}}
單詞邊界匹配器 /b
/b代表一個單詞的開始和結束部分,不匹配任何字符
總結
以上所述是小編給大家介紹的Java 使用正則表達式對象實現正則的獲取功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答
圖片精選