Java 使用正則表達(dá)式對象實(shí)現(xiàn)正則的獲取功能
獲取需要使用到正則的兩個對象:
使用的是用正則對象Pattern 和匹配器Matcher。
用法:
范例:
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();
步驟:
1,先將正則表達(dá)式編譯成正則對象。使用的是Pattern類一個靜態(tài)的方法。compile(regex);
2,讓正則對象和要操作的字符串相關(guān)聯(lián),通過matcher方法完成,并返回匹配器對象。
3,通過匹配器對象的方法將正則模式作用到字符串上對字符串進(jìn)行針對性的功能操作
需求:獲取由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ī)則對字符串進(jìn)行匹配查找。
// System.out.println(m.find());//將規(guī)則對字符串進(jìn)行匹配查找。
// 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)絡(luò)爬蟲 (獲取郵箱)
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 使用正則表達(dá)式對象實(shí)現(xiàn)正則的獲取功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
幾個小例子教你如何實(shí)現(xiàn)正則表達(dá)式highlight高亮
正則表達(dá)式,用起來還是挺方便的。正則技能,你值得擁有??!2014-05-05
java正則表達(dá)式獲取大括號小括號內(nèi)容并判斷數(shù)字和小數(shù)親測可用
這篇文章主要介紹了java正則表達(dá)式獲取大括號小括號內(nèi)容并判斷數(shù)字和小數(shù)親測可用,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-06-06
javascript中使用正則表達(dá)式實(shí)現(xiàn)刪除字符串中的前后空格
在前臺應(yīng)用進(jìn)我們經(jīng)常會碰到要刪除用戶輸入的字符中的空格的問題,下面我們來介紹一下javascript中使用正則表達(dá)式實(shí)現(xiàn)刪除字符串中的空格方法2012-09-09
關(guān)于內(nèi)容的分離,正則抽出圖片(一定要加精哦)
我們在加內(nèi)容時,無論你怎么樣排版都好,我們都是無法將里面的圖片或是別的什么東西抽出來的.2009-01-01

