javaRegex簡單使用和網頁爬蟲的製作代碼

來源:互聯網
上載者:User

Regex是一種專門用於對字串的操作的規則。

1.在String類中就有一些方法是對字串進行匹配,切割。

判斷字串是否與給出的Regex匹配的:boolean matches( String regex);

按照給定的Regex對字串進行切割的:String[] split(String regex);

將符合Regex的字串替換成我們想要的其他字串:String replaceAll(String regex,String replacement)

2.下面介紹一下Regex常用的用法

(1)

複製代碼 代碼如下:String regex="[1-9][0-9]{4,15}";
//[1-9]表示這個數字只能在1-9內選擇
//[0-9]表示這個數字可以是0-9
//{4,15}表示其前面的這個格式的數字可以重複4-15次

這個Regex的意思 是:第一個數字應該是1-9中任意的一個,然後緊接著就必須要出現0-9中的數字中的一種,而且這種數字至少要出現4次,至多出現15次

如:

10175 符合

10不符合,因為[0-9]{4,15},至少要出現4次以上,在這裡只出現了一次

(2)

[a-zA-Z0-9_]{6}表示恰好要出現6次a-z或A-Z或_ 中的字元

+表示至少出現一次

*表示出現0次或多次

?表示出現一次或0次

(3)根據Regex來切割字串

複製代碼 代碼如下:String str="sjd.ksdj.skdjf";

String regex="\\.";

注意: . 在Regex中是表式一個任意的字元,是一個特殊的符號。我們想要用.來切割,就必須將其轉換為一般字元 用\\即可。

因為\ 也是特殊符號,所以要兩個\\來表示。當我們想要使用普通的 \ 時,那麼就要用\\\\來表示才可。

String[] ss=str.split(regex); 返回字串數組: "sjd" "ksdj" "skdjf" 實現 了對原有字串的切割

(4)根據Regex來替換掉我們想要替換的東西

將字串中所有連續出現5個或以上的數字串替換成#

複製代碼 代碼如下:String str="abcd1334546lasjdfldsf2343424sdj";

String regex="[0-9]{5,}";

String newstr=str.replaceAll(regex,"#");

(5)擷取符合Regex規則的字串

複製代碼 代碼如下:Pattern p=Pattern.compile(String regex);

Matcher m=p.matcher(String str);

while(m.find())

{

System.out.println(m.group());

}

3.網頁爬蟲的製作

我們製作 一個可以將一個網頁中的全部的郵箱讀取出,並且存放在一個文字檔中。

複製代碼 代碼如下:/*
網頁爬蟲
即:從網頁中擷取符合Regex的字串或內容

從網路中擷取郵箱地址
*/
import java.io.*;
import java.util.regex.*;
import java.net.*;
class MailTest
{
public static void main(String[] args) throws Exception
{
getMailAddr();
}

public static void getMailAddr()throws Exception
{
URL url=new URL("http://bbs.jb51.net/topics/390148495");
URLConnection con=url.openConnection();

BufferedReader bufIn=new BufferedReader(new InputStreamReader(con.getInputStream()));
BufferedWriter bufw=new BufferedWriter(new FileWriter(new File("e://mailaddress.txt")));
String str=null;
String regex="[a-zA-Z0-9_]{6,12}@[a-zA-Z0-9]+(\\.[a-zA-Z]+)+";

Pattern p=Pattern.compile(regex);
while((str=bufIn.readLine())!=null)
{
Matcher m=p.matcher(str);
while(m.find())
{
String ss=m.group();
bufw.write(ss,0,ss.length());
bufw.newLine();
bufw.flush();
}
}

}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.