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

use*_*834 2 java regex solr

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

http://mycompany.com/test/id/1234#this
Run Code Online (Sandbox Code Playgroud)

所以我只想得到1234.

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

".*/(.*)(#|$)",
Run Code Online (Sandbox Code Playgroud)

索引数据时我需要这个,所以不想使用URL类.

fge*_*fge 5

只需使用URI:

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

还将使用查询字符串等来处理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));
}
Run Code Online (Sandbox Code Playgroud)