java - 模式匹配并使用 java 从 URL 获取多个值
问题描述
我正在使用 Java-8,我想根据模式检查 URL 是否有效。如果有效,那么我应该获取属性 bookId、authorId、category、mediaId
Pattern: <basepath>/books/<bookId>/author/<authorId>/<isbn>/<category>/mediaId/<filename>
这是示例网址
URL => https:/<baseurl>/v1/files/library/books/1234-4567/author/56784589/32475622347586/media/324785643257567/507f1f77bcf86cd799439011_400.png
这里 Basepath 是 /v1/files/library。
我看到了一些模式匹配,但我无法与我的用例联系起来,可能我不擅长 reg-ex。我也在使用 apache-common-utils 但我也不确定如何实现它。
任何帮助或提示将是非常可观的。
解决方案
试试这个解决方案(在正则表达式中使用命名的捕获组):
public static void main(String[] args)
{
Pattern p = Pattern.compile("http[s]?:.+/books/(?<bookId>[^/]+)/author/(?<authorId>[^/]+)/(?<isbn>[^/]+)/media/(?<mediaId>[^/]+)/(?<filename>.+)");
Matcher m = p.matcher("https:/<baseurl>/v1/files/library/books/1234-4567/author/56784589/32475622347586/media/324785643257567/507f1f77bcf86cd799439011_400.png");
if (m.matches())
{
System.out.println("bookId = " + m.group("bookId"));
System.out.println("authorId = " + m.group("authorId"));
System.out.println("isbn = " + m.group("isbn"));
System.out.println("mediaId = " + m.group("mediaId"));
System.out.println("filename = " + m.group("filename"));
}
}
印刷:
bookId = 1234-4567
authorId = 56784589
isbn = 32475622347586
mediaId = 324785643257567
filename = 507f1f77bcf86cd799439011_400.png
推荐阅读
- php - Docker Compose:从 Dockerfile 在 php.ini 中设置变量
- node.js - 构建 Node.js 和 Socket.io 应用程序的最佳实践?
- mpdf - mPDF 分页条件
- spring - Spring Boot 微服务 Maven 架构
- c++ - 如何使用赋值运算符声明函数?
- java - 如何在不影响活跃用户的情况下测试您的应用?
- r - 如何从 tidyverse 中的线性回归计算几个斜率
- airflow - Airflow Dag 未按计划的时间间隔运行
- java - 构建输出文件“buildConfig.java”在 Android Studio 中有 null 布尔错误
- javascript - 我如何在springboot中的jsp文件中导入js文件