獲取需要使用到正則的兩個對象:
使用的是用正則對象Pattern 和匹配器Matcher。
用法:
范例:
Pattern p = Pattern.compile("a*b"); Matcher m = p.matcher("aaaaab"); boolean b = m.matches();
步驟:
1,先將正則表達式編譯成正則對象。使用的是Pattern類一個靜態(tài)的方法。compile(regex);
2,讓正則對象和要操作的字符串相關(guān)聯(lián),通過matcher方法完成,并返回匹配器對象。
3,通過匹配器對象的方法將正則模式作用到字符串上對字符串進行針對性的功能操作
需求:獲取由3個字母組成的單詞。
public static void getDemo() { String str = "da jia zhu yi le,ming tian bu fang jia,xie xie!"; //想要獲取由3個字母組成的單詞。 //剛才的功能返回的都是一個結(jié)果,只有split返回的是數(shù)組,但是它是把規(guī)則作為分隔符,不會獲取符合規(guī)則的內(nèi)容。 //這時我們要用到一些正則對象。 String reg = "\\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());//將規(guī)則對字符串進行匹配查找。 // System.out.println(m.find());//將規(guī)則對字符串進行匹配查找。 // System.out.println(m.group());//在使用group方法之前,必須要先找,找到了才可以取。 }
校驗郵件
public static void checkMail() { String mail = "abc123@sina.com.cn"; mail = "1@1.1"; String reg = "[a-zA-Z_0-9]+@[a-zA-Z0-9]+(\\.[a-zA-Z]+)+"; reg = "\\w+@\\w+(\\.\\w+)+";//簡化的規(guī)則?;\統(tǒng)的匹配。 boolean b = mail.matches(reg); System.out.println(mail+":"+b); }
網(wǎng)絡爬蟲 (獲取郵箱)
class GetMailList { public static void main(String[] args) throws Exception { String reg = "\\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代表一個單詞的開始和結(jié)束部分,不匹配任何字符
總結(jié)
以上所述是小編給大家介紹的Java 使用正則表達式對象實現(xiàn)正則的獲取功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
上一篇:C#中正則表達式與回車換行符問題
下一篇:深入淺析正則表達式中的\B和\b