在 Web 應用開發中,我們經常需要對 URL 進行格式驗證。今天我們結合 Java 的 Pattern
和 Matcher
類,深入理解正則表達式在實際應用中的強大功能,并剖析一段實際的 Java 示例源碼。
?
package com.RegExpInfo;import java.util.regex.Matcher;
import java.util.regex.Pattern;public class Exercise02 {public static void main(String[] args) {
// String content="https://";
// String content="http://";
// String content="https://" +
// "www.bilibili.com/";
// String content="https://" +
// "www.bilibili.com/" +
// "video/" +
// "BV1fh411y7R8?spm_id_from=333.788.player.switch&vd_" +
// "source=6fe96db28441a84c79edc35a022cf1c5&p=895" ;
// String content="https://" +
// "www.bilibili.com" ;String content="https://blog.csdn.net/keshi12354?spm=1000.2115.3001.5343";
// String regExp="^((https|http)://)";
// (2)
// String regExp="^((https|http)://)([\\w-]+\\.)+[\\w-]+\\/";
// (3)String regExp="^((https|http)://)([\\w-]+\\.)+[\\w-]+(\\/([\\w-_?=&./]*))?$";
// String regExp="^((https|http)://)([\\w-]+\\.)+[\\w-]+(\\/([\\w-_?=&./]*))?$";Pattern pattern = Pattern.compile(regExp);Matcher matcher = pattern.matcher(content);while (matcher.find()) {System.out.println(matcher.group(0));}}
}
1.正則表達式分解:
分布實現:
1. 基礎協議匹配?(1)
String regExp="^((https|http)://)";
-
功能:只匹配URL開頭的協議部分
-
匹配內容:
http://
?或?https://
-
結構:
-
^
?表示字符串開始 -
(https|http)
?匹配"https"或"http" -
://
?匹配協議分隔符
-
-
目的:先確保能正確識別URL的協議部分
2. 添加域名匹配?(2)
String regExp="^((https|http)://)([\\w-]+\\.)+[\\w-]+\\/";
-
新增功能:在協議后添加域名和路徑的基本匹配
-
匹配內容:如?
http://example.com/
-
新增結構:
-
([\\w-]+\\.)+
?匹配一個或多個域名部分(如"www."或"sub.")-
\\w
?匹配單詞字符(字母、數字、下劃線) -
-
?匹配連字符 -
+
?表示一次或多次 -
\\.
?匹配點號
-
-
[\\w-]+
?匹配頂級域名(如"com") -
\\/
?匹配結尾的斜杠
-
-
目的:擴展匹配完整的域名結構
?
3. 添加路徑和查詢參數匹配?(3)
String regExp="^((https|http)://)([\\w-]+\\.)+[\\w-]+(\\/([\\w-_?=&./]*))?$";
-
新增功能:支持可選的路徑和查詢參數
-
匹配內容:如?
http://example.com/path?param=value
-
新增結構:
-
(\\/([\\w-_?=&./]*))?
-
\\/
?匹配路徑開始的斜杠 -
[\\w-_?=&./]*
?匹配路徑和查詢參數-
包含字母、數字、下劃線、連字符、問號、等號、&、點和斜杠
-
-
?
?表示整個路徑部分是可選的
-
-
$
?表示字符串結束
-
-
目的:使正則表達式能夠匹配帶路徑和參數的完整URL
?4. 最終優化版本
String regExp="^((https|http)://)?([\\w-]+\\.)+[\\w-]+(\\/([\\w-_?=&./]*))?$";
-
關鍵改進:使協議部分變為可選
-
匹配內容:現在可以匹配:
-
帶協議的URL:
http://example.com/path
-
不帶協議的URL:
example.com/path
-
-
修改點:
-
在協議部分?
((https|http)://)
?后添加了??
?使其變為可選
-
-
目的:提高正則表達式的靈活性,適應更多使用場景
5.設計思想總結
-
漸進式開發:從簡單到復雜逐步構建正則表達式
-
模塊化設計:每個部分都有明確的功能劃分(協議、域名、路徑)
-
靈活性增強:通過添加可選標記(
?
)使表達式更通用 -
邊界明確:始終使用
^
和$
確保匹配整個字符串 -
字符集合理定義:使用
[\w-]
等字符集準確描述允許的字符
這種分步構建的方法不僅使正則表達式更易于理解和維護,也方便在開發過程中逐步測試每個部分的匹配效果。