使用正则表达式获取URL的最后一部分

3
我如何使用正则表达式获取URL的最后一部分?这是我的URL,我想要在最后一个斜杠和 # 之间的部分。
http://mycompany.com/test/id/1234#this

我只想获得 1234

我有以下代码,但未删除“#this”。

".*/(.*)(#|$)",

在索引数据时,我需要这个东西,所以不想使用URL类。


1
必须使用正则表达式吗?为什么不使用字符串方法,例如substring、lastIndexOf等呢? - Jim
@Jim,JDK本身还有更好的选择。 - fge
3个回答

5
只需使用URI:
final URI uri = URI.create(yourInput);
final String path = uri.getPath();
path.substring(path.lastIndexOf('/') + 1); // will return what you want

还可以处理带查询字符串等的URI。需要从URL中提取任何部分时(URL实际上是URI),使用正则表达式不是您想要的:URI可以为您处理所有内容,并且成本更低,因为它具有专用解析器。

演示代码还使用Guava的Optional来检测URI没有路径组件的情况:

public static void main(final String... args) {
    final String url = "http://mycompany.com/test/id/1234#this";
    final URI uri = URI.create(url);
    final String path = Optional.fromNullable(uri.getPath()).or("/");
    System.out.println(path.substring(path.lastIndexOf('/') + 1));
}

3
怎么样:
".*/([^/#]*)(#.*|$)"

如果有任何查询字符串,将会失败。 - fge

0

除了@jtahlborn的回答外,补充包括查询字符串:

".*/([^/#|?]*)(#.*|$)"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接