【问题标题】:Get last part of url using a regex使用正则表达式获取 url 的最后一部分
【发布时间】:2013-07-24 15:41:58
【问题描述】:

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

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

所以我只想得到1234

我有以下内容,但没有删除“#this”

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

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

【问题讨论】:

  • 必须是正则表达式吗?为什么不使用 String 方法,例如 substring、lastIndexOf 等?
  • @Jim 比 JDK 本身更好

标签: java regex solr


【解决方案1】:

只需使用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));
}

【讨论】:

    【解决方案2】:

    怎么样:

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

    【讨论】:

    • 如果里面有任何查询字符串会失败。
    猜你喜欢
    • 2018-08-18
    • 1970-01-01
    • 2010-09-06
    • 2015-02-20
    • 2014-09-04
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 2012-02-06
    相关资源
    最近更新 更多