使用java进行模式匹配并从URL获取多个值

使用java进行模式匹配并从URL获取多个值,java,regex,apache-commons,Java,Regex,Apache Commons,我正在使用Java-8,我想根据模式检查URL是否有效。 如果有效,那么我应该获取bookId、authorId、category和mediaId属性 Pattern: <basepath>/books/<bookId>/author/<authorId>/<isbn>/<category>/mediaId/<filename> Pattern:/books//author///mediaId/ 这是示例URL URL

我正在使用Java-8,我想根据模式检查URL是否有效。 如果有效,那么我应该获取bookId、authorId、category和mediaId属性

Pattern: <basepath>/books/<bookId>/author/<authorId>/<isbn>/<category>/mediaId/<filename>
Pattern:/books//author///mediaId/
这是示例URL

URL => https:/<baseurl>/v1/files/library/books/1234-4567/author/56784589/32475622347586/media/324785643257567/507f1f77bcf86cd799439011_400.png
URL=>https://v1/files/library/books/1234-4567/author/56784589/32475622347586/media/324785643257567/507f1f77bcf86cd799439011_400.png
这里的Basepath是/v1/files/library

我看到了一些模式匹配,但我无法与我的用例联系起来,可能我不擅长reg-ex。我也在使用apache common UTIL,但我也不确定如何实现它

任何帮助或提示都非常有用。

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


您尝试过什么正则表达式,或者您只是希望我们为您编写代码?@Andreas我在正则表达式中使用了subStringBetween和subStringAfter从url获取值,但我不知道如何编写模式来检查它是否有效。我也在努力。如果我接近“subStringBetween和subStringAfter in regEx”是什么意思?显示您尝试过的正则表达式。我正在获取字符串中的整个url…因此使用commons stringUtils获取字符串中url之间的值,因为url中几乎没有固定的属性,如book、author等“我获取整个url”(单数),然后是“url之间的值”(复数)。这是什么意思?您有1个或多个URL吗?这与正则表达式有什么关系呢?添加
[^/]+
应该是
[^/?#]+
,因为
将终止URL的路径部分。
    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