Java 正则表达式:如何匹配 URL 路径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24538991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Regex: How to Match URL Path?
提问by David Williams
I am trying to extract the first part of the path of a URL. For example: from http://foo.com/bar/1/2/3
I want to extract bar
. Here is the code I am using:
我正在尝试提取 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;
}
However, this does not match the most trivial url listed above, as in
但是,这与上面列出的最简单的 url 不匹配,如
public static void main(String[] args)
{
getFirstPartOfPath("http://foo.com/bar/1/2/3");
}
prints nothing. At first glance the pattern string seems clear and like it should obviously work. What is going wrong?
什么都不打印。乍一看,模式字符串似乎很清楚,而且显然应该可以工作。出了什么问题?
采纳答案by anubhava
Not matching because your regex is not correct. You have /*
in the end that is not same as /.*
.
不匹配,因为您的正则表达式不正确。你/*
到底有什么不一样/.*
。
Use this regex:
使用这个正则表达式:
Pattern pattern = Pattern.compile("^https?://[^/]+/([^/]+)/.*$");
Or remove anchor $
:
或删除锚点$
:
Pattern pattern = Pattern.compile("^https?://[^/]+/([^/]+)/");