programing

URI의 마지막 경로세그먼트를 취득하는 방법

sourcejob 2022. 9. 29. 00:13
반응형

URI의 마지막 경로세그먼트를 취득하는 방법

입력된 문자열이 있습니다.URI마지막 패스 세그먼트(이 경우는 ID)를 취득할 수 있는 방법은 무엇입니까?

입력 URL은 다음과 같습니다.

String uri = "http://base_path/some_segment/id"

이것으로 시도한 ID를 취득해야 합니다.

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

하지만 효과가 없고, 분명히 더 나은 방법이 있을 거야.

이것이 당신이 찾고 있는 것입니다.

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);

대신해서

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);
import android.net.Uri;
Uri uri = Uri.parse("http://example.com/foo/bar/42?param=true");
String token = uri.getLastPathSegment();

간단한 방법은 다음과 같습니다.

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

테스트 코드:

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/"));
}

출력:

42
후우
막대기

설명:

.*/      // 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

이것이 오래되었다는 것을 알지만, 이곳의 해결책은 다소 장황하게 보인다.한 줄짜리만 있으면 쉽게 읽을 수 있습니다.URL또는URI:

String filename = new File(url.getPath()).getName();

또는,String:

String filename = new File(new URL(url).getPath()).getName();

Java 8을 사용하는 경우 파일 경로의 마지막 세그먼트를 사용할 수 있습니다.

Path path = Paths.get("example/path/to/file");
String lastSegment = path.getFileName().toString();

다음과 같은 URL이 있는 경우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);

Android의 경우

Android에는 URI를 관리하기 위한 클래스가 내장되어 있습니다.

Uri uri = Uri.parse("http://base_path/some_segment/id");
String lastPathSegment = uri.getLastPathSegment()

가지고 계신 경우commons-io불필요한 오브젝트를 작성하지 않고 프로젝트를 수행할 수 있습니다.org.apache.commons.io.FilenameUtils

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

이 경로의 마지막 부분인id

Java 7+에서는 이전 응답 중 몇 가지를 조합하여 마지막 세그먼트뿐만 아니라 URI에서 모든 경로세그먼트를 취득할 수 있습니다.URI를 오브젝트로 변환하여 그 메서드를 활용할 수 있습니다.

불행히도, 정전기 공장은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();

코드 한 줄의 마지막 세그먼트를 가져오려면 위의 행을 중첩하십시오.

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

인덱스 번호와 오프바이원 오류 가능성을 피하면서 두 번째에서 마지막까지의 세그먼트를 가져오려면 이 방법을 사용합니다.

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

주의:getParent()메서드를 반복적으로 호출하여 세그먼트를 역순으로 검색할 수 있습니다.이 예에서는, 패스에 포함되는 세그먼트는 2개 뿐입니다.그 이외의 경우는,getParent().getParent()세 번째에서 마지막 세그먼트를 가져옵니다.

사용할 수 있습니다.getPathSegments()기능(Android 설명서)

예를 들어 URI를 생각해 보겠습니다.

String uri = "http://base_path/some_segment/id"

마지막 세그먼트는 다음 방법으로 얻을 수 있습니다.

List<String> pathSegments = uri.getPathSegments();
String lastSegment = pathSegments.get(pathSegments.size - 1);

lastSegment될 것이다id.

replaceAll을 사용할 수도 있습니다.

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

System.out.println(lastSegment);

결과:

id

유틸리티 클래스에서 다음을 사용하고 있습니다.

public static String lastNUriPathPartsOf(final String uri, final int n, final String... ellipsis)
  throws URISyntaxException {
    return lastNUriPathPartsOf(new URI(uri), n, ellipsis);
}

public static String lastNUriPathPartsOf(final URI uri, final int n, final String... ellipsis) {
    return uri.toString().contains("/")
        ? (ellipsis.length == 0 ? "..." : ellipsis[0])
          + uri.toString().substring(StringUtils.lastOrdinalIndexOf(uri.toString(), "/", n))
        : uri.toString();
}

URI 클래스에서 경로 세그먼트 목록을 가져올 수 있습니다.

String id = Uri.tryParse("http://base_path/some_segment/id")?.pathSegments.last ?? "InValid URL";

URL이 올바르면 ID를 반환하고, 올바르지 않으면 "Invalid url"을 반환합니다.

URI 에서 URL 을 취득해, 파일의 추출에 서브스트링 방식을 사용할 준비가 되어 있지 않은 경우는, get File() 를 사용합니다.

언급URL : https://stackoverflow.com/questions/4050087/how-to-obtain-the-last-path-segment-of-a-uri

반응형