JAVA筆記:正則表達式

簡介

正則表達式一般適用於複雜文本的處理,是強大又靈活的文本處理工具,幾乎所有的編程語言都支持正則表達式。主要是通過一個規則匹配一類字符串

正則表達式規則

在這裏插入圖片描述圖源於百度,侵權刪。
一直保存了這個圖片,個人覺得這個圖就夠大部分正則表達式使用了

正則表達式的使用

在JAVA中java,util.regex包下已經封裝好了大部分的方法
核心類:
Pattern:
正則表達式的編譯表示形式。
Pattern p = Pattern. compile ( r,int ) ; //建立正則表達式,並啓用相應模式
Matcher:
與 Pattern 一起使用,對character[]執行匹配操作
Matcher m = p.matcher(str); //匹配str字符串

使用步驟:
1、創建表達式
2、創建Matcher對象
3、對結果操作

Demo

		Pattern p = Pattern.compile("([a-z]+)([0-9]+)");
		Matcher m = p.matcher("hello23333hi");
		while(m.find()) {
			System.out.println(m.group());//==>group(0)匹配整個字符串//hello23333
			System.out.println(m.group(1));//hello
			System.out.println(m.group(2));//23333
		}

推薦一個測試正則的app——RegexBuddy.exe
在這裏插入圖片描述挺好用的一個測試正則表達式程序

Demo
爬取網站,得到超鏈接

@Test
	void test() throws Exception {
		StringBuilder sb = new StringBuilder();
		URL url = new URL("http://www.163.com");
		//部分網頁需要模擬請求
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("GET");
		//
		connection.setRequestProperty("User-Agent", 
				"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36");
		BufferedReader reader = new BufferedReader(
				new InputStreamReader(connection.getInputStream(),Charset.forName("gbk")));
		String result = "";
		while((result = reader.readLine())!=null) {
			sb.append(result);
		}
		//匹配所有的超鏈接
		Pattern pattern = Pattern.compile("href=\"([a-zA-Z]+:\\/\\/[^\\s]+)\"");
		Matcher m = pattern.matcher(sb.toString());
		while(m.find()) {
			System.out.println(m.group(1));
		}
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章