在 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-]
等字符集准确描述允许的字符
这种分步构建的方法不仅使正则表达式更易于理解和维护,也方便在开发过程中逐步测试每个部分的匹配效果。