繁体   English   中英

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

[英]Get last part of url using a regex

如何使用正则表达式获取 URL 的最后一部分,这是我的 URL,我想要最后一个正斜杠和 # 之间的段

http://mycompany.com/test/id/1234#this

所以我只想得到1234

我有以下但没有删除'#this'

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

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

只需使用URI

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

还将处理带有查询字符串等的URI。在任何情况下,当必须从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));
}

怎么样:

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

除了@jtahlborn回答包括查询字符串:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM