欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java 使用正則表達(dá)式對(duì)象實(shí)現(xiàn)正則的獲取功能

 更新時(shí)間:2018年04月12日 10:26:53   作者:qq_17503037  
這篇文章主要介紹了Java 使用正則表達(dá)式對(duì)象實(shí)現(xiàn)正則的獲取功能 ,需要的朋友可以參考下

獲取需要使用到正則的兩個(gè)對(duì)象:

使用的是用正則對(duì)象Pattern 和匹配器Matcher。

用法:

范例:

 Pattern p = Pattern.compile("a*b");
 Matcher m = p.matcher("aaaaab");
 boolean b = m.matches();

步驟:

1,先將正則表達(dá)式編譯成正則對(duì)象。使用的是Pattern類一個(gè)靜態(tài)的方法。compile(regex);

2,讓正則對(duì)象和要操作的字符串相關(guān)聯(lián),通過(guò)matcher方法完成,并返回匹配器對(duì)象。

3,通過(guò)匹配器對(duì)象的方法將正則模式作用到字符串上對(duì)字符串進(jìn)行針對(duì)性的功能操作

需求:獲取由3個(gè)字母組成的單詞。

public static void getDemo()
{
  String str = "da jia zhu yi le,ming tian bu fang jia,xie xie!";
  //想要獲取由3個(gè)字母組成的單詞。
  //剛才的功能返回的都是一個(gè)結(jié)果,只有split返回的是數(shù)組,但是它是把規(guī)則作為分隔符,不會(huì)獲取符合規(guī)則的內(nèi)容。
  //這時(shí)我們要用到一些正則對(duì)象。
  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ī)則對(duì)字符串進(jìn)行匹配查找。
//   System.out.println(m.find());//將規(guī)則對(duì)字符串進(jìn)行匹配查找。
//   System.out.println(m.group());//在使用group方法之前,必須要先找,找到了才可以取。
}

校驗(yàn)郵件

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+)+";//簡(jiǎn)化的規(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代表一個(gè)單詞的開始和結(jié)束部分,不匹配任何字符

總結(jié)

以上所述是小編給大家介紹的Java 使用正則表達(dá)式對(duì)象實(shí)現(xiàn)正則的獲取功能,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評(píng)論