首页 > 解决方案 > 模式匹配并使用 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 但我也不确定如何实现它。

任何帮助或提示将是非常可观的。

标签: javaregexapache-commons

解决方案


试试这个解决方案(在正则表达式中使用命名的捕获组):

    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

推荐阅读