java match url_Java Regex:如何匹配URL路径?(Java Regex: How to Match URL Path?)
Java Regex:如何匹配URL路径?(Java Regex: How to Match URL Path?)
我试图提取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;
}
但是,这与上面列出的最琐碎的网址不匹配,如
public static void main(String[] args)
{
getFirstPartOfPath("http://foo.com/bar/1/2/3");
}
没有打印。 乍一看,模式字符串看起来很清晰,就像它显然应该工作一样。 出了什么问题?
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:
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
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?
原文:https://stackoverflow.com/questions/24538991
2019-12-06 13:12
满意答案
不匹配
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
