【问题标题】:Java Regex: How to Match URL Path?Java 正则表达式:如何匹配 URL 路径?
【发布时间】:2014-08-23 17:01:02
【问题描述】:

我正在尝试提取 URL 路径的第一部分。例如:从http://foo.com/bar/1/2/3我要提取bar。这是我正在使用的代码:

private static String getFirstPartOfPath(String url)
{
    Pattern pattern = Pattern.compile("^https?://[^/]+/([^/]+)/*$");
    Matcher matcher = pattern.matcher(url);
    if(matcher.find())
    {
        System.out.println(matcher.group(1));
    }
    return null;
}

但是,这与上面列出的最琐碎的 url 不匹配,如

public static void main(String[] args)
{
    getFirstPartOfPath("http://foo.com/bar/1/2/3");
}

什么都不打印。乍一看,模式字符串似乎很清晰,并且显然应该可以工作。出了什么问题?

【问题讨论】:

    标签: java regex url


    【解决方案1】:

    不匹配,因为您的正则表达式不正确。你最后有/*/.* 不一样。

    使用这个正则表达式:

    Pattern pattern = Pattern.compile("^https?://[^/]+/([^/]+)/.*$");
    

    或者删除锚$

    Pattern pattern = Pattern.compile("^https?://[^/]+/([^/]+)/");
    

    【讨论】:

    • 知道了,谢谢。当 SO 允许我在 9 分钟内时,我会接受。
    猜你喜欢
    • 2022-08-11
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 2023-01-31
    • 2012-02-04
    • 2016-12-11
    • 2020-08-19
    • 1970-01-01
    相关资源
    最近更新 更多