如何获取uri的最后一个路径段

DX8*_*89B 101 java string url

我输入了一个字符串URI.怎么可能得到最后一个路径段?在我的情况下是一个id?

这是我输入的网址

String uri = "http://base_path/some_segment/id"
Run Code Online (Sandbox Code Playgroud)

而且我必须获得我尝试过的这个ID

String strId = "http://base_path/some_segment/id";
strId=strId.replace(path);
strId=strId.replaceAll("/", "");
Integer id =  new Integer(strId);
return id.intValue();
Run Code Online (Sandbox Code Playgroud)

但它不起作用,肯定有更好的方法来做到这一点.

sfu*_*ger 161

是你在找什么:

URI uri = new URI("http://example.com/foo/bar/42?param=true");
String path = uri.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
int id = Integer.parseInt(idStr);
Run Code Online (Sandbox Code Playgroud)

或者

URI uri = new URI("http://example.com/foo/bar/42?param=true");
String[] segments = uri.getPath().split("/");
String idStr = segments[segments.length-1];
int id = Integer.parseInt(idStr);
Run Code Online (Sandbox Code Playgroud)

  • 我正在搜索Android的android.net.Uri(不是java.net.URI)并最终在这里.如果您正在使用它,那么有一个名为getLastPathSegment()的方法应该做同样的事情.:) (46认同)
  • 只需执行`String idStr = new File(uri.getPath()).getName()`,与此答案相同,但使用`File`而不是`String`来分割路径. (5认同)

Col*_*ral 63

import android.net.Uri;
Uri uri = Uri.parse("http://example.com/foo/bar/42?param=true");
String token = uri.getLastPathSegment();
Run Code Online (Sandbox Code Playgroud)

  • 这是“android.net.Uri”吗?基于问题的标签,将假定 java.net.URI 并且它没有 getLastPathSegment()... (2认同)
  • 它确实有 getLastPathSegment() 但它不起作用!返回空! (2认同)

Sea*_*oyd 47

这是一个简短的方法:

public static String getLastBitFromUrl(final String url){
    // return url.replaceFirst("[^?]*/(.*?)(?:\\?.*)","$1);" <-- incorrect
    return url.replaceFirst(".*/([^/?]+).*", "$1");
}
Run Code Online (Sandbox Code Playgroud)

测试代码:

public static void main(final String[] args){
    System.out.println(getLastBitFromUrl(
        "http://example.com/foo/bar/42?param=true"));
    System.out.println(getLastBitFromUrl("http://example.com/foo"));
    System.out.println(getLastBitFromUrl("http://example.com/bar/"));
}
Run Code Online (Sandbox Code Playgroud)

输出:

42
foo

说明:

.*/      // find anything up to the last / character
([^/?]+) // find (and capture) all following characters up to the next / or ?
         // the + makes sure that at least 1 character is matched
.*       // find all following characters


$1       // this variable references the saved second group from above
         // I.e. the entire string is replaces with just the portion
         // captured by the parentheses above
Run Code Online (Sandbox Code Playgroud)


Jas*_*n C 22

我知道这是旧的,但这里的解决方案似乎相当冗长.如果你有一个URL或者只是一个容易阅读的单行内容URI:

String filename = new File(url.getPath()).getName();
Run Code Online (Sandbox Code Playgroud)

或者,如果您有String:

String filename = new File(new URL(url).getPath()).getName();
Run Code Online (Sandbox Code Playgroud)

  • @alik该问题要求最后一个路径段。查询和片段不是路径段的一部分。 (3认同)

Wil*_*eys 9

如果您使用的是Java 8,并且希望文件路径中的最后一个段可以执行.

Path path = Paths.get("example/path/to/file");
String lastSegment = path.getFileName().toString();
Run Code Online (Sandbox Code Playgroud)

如果你有一个http://base_path/some_segment/id你可以做的网址.

final Path urlPath = Paths.get("http://base_path/some_segment/id");
final Path lastSegment = urlPath.getName(urlPath.getNameCount() - 1);
Run Code Online (Sandbox Code Playgroud)

  • 风险因为java.nio.file.Paths#get取决于运行JVM的OS文件系统.无法保证它会识别带有正斜杠的URI作为路径分隔符. (3认同)
  • 带有查询参数的 URI 怎么样?将随机 URI 视为文件系统路径是在请求异常。 (2认同)

jac*_*646 7

在Java 7+中,可以组合以前的一些答案,以允许从URI中检索任何路径段,而不仅仅是最后一段.我们可以将URI转换为java.nio.file.Path对象,以利用其getName(int)方法.

不幸的是,静态工厂Paths.get(uri)不是为了处理http方案而构建的,所以我们首先需要将方案与URI的路径分开.

URI uri = URI.create("http://base_path/some_segment/id");
Path path = Paths.get(uri.getPath());
String last = path.getFileName().toString();
String secondToLast = path.getName(path.getNameCount() - 2).toString();
Run Code Online (Sandbox Code Playgroud)

要在一行代码中获取最后一段,只需将上面的行嵌套.

Paths.get(URI.create("http://base_path/some_segment/id").getPath()).getFileName().toString()

要获得倒数第二个段,同时避免索引号和可能出现的逐个错误,请使用该getParent()方法.

String secondToLast = path.getParent().getFileName().toString();

请注意,getParent()可以重复调用该方法以按相反顺序检索段.在此示例中,路径仅包含两个段,否则调用getParent().getParent()将检索倒数第三个段.


Bri*_*pin 7

在Android中

Android有一个用于管理URI的内置类.

Uri uri = Uri.parse("http://base_path/some_segment/id");
String lastPathSegment = uri.getLastPathSegment()
Run Code Online (Sandbox Code Playgroud)


Bnr*_*rdo 6

如果你已经commons-io包含在你的项目中,你可以不用创建不必要的对象org.apache.commons.io.FilenameUtils

String uri = "http://base_path/some_segment/id";
String fileName = FilenameUtils.getName(uri);
System.out.println(fileName);
Run Code Online (Sandbox Code Playgroud)

会给你路径的最后一部分,也就是 id


Sin*_*adi 5

您可以使用getPathSegments()函数。(安卓文档

考虑您的示例 URI:

String uri = "http://base_path/some_segment/id"
Run Code Online (Sandbox Code Playgroud)

您可以使用以下方法获取最后一段:

List<String> pathSegments = uri.getPathSegments();
String lastSegment = pathSegments.get(pathSegments.size() - 1);
Run Code Online (Sandbox Code Playgroud)

lastSegmentid


Krz*_*cki 5

您还可以使用 replaceAll:

String uri = "http://base_path/some_segment/id"
String lastSegment = uri.replaceAll(".*/", "")

System.out.println(lastSegment);
Run Code Online (Sandbox Code Playgroud)

结果:

id
Run Code Online (Sandbox Code Playgroud)