You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用字符串函数提取API路径中最后斜杠后的动态ID?

提取URL路径中最后一个斜杠后的动态ID

针对你给出的路径字符串,不管使用哪种编程语言,核心思路都是定位最后一个/的位置,然后截取其后的内容,或者通过分割字符串取最后一段。以下是几种主流语言的实现方式:

Python

方法1:使用rsplit(推荐)

只从右侧分割一次,直接取最后一段:

path = '/api/media-objects/e78c7cfa-e469-4edd-8a87-9517a5b9e5da'
target_id = path.rsplit('/', 1)[-1]

方法2:使用rfind定位后切片

先找到最后一个/的索引,再截取后续内容:

path = '/api/media-objects/e78c7cfa-e469-4edd-8a87-9517a5b9e5da'
slash_index = path.rfind('/')
target_id = path[slash_index + 1:]

JavaScript

方法1:split + pop

分割成数组后弹出最后一个元素:

const path = '/api/media-objects/e78c7cfa-e469-4edd-8a87-9517a5b9e5da';
const targetId = path.split('/').pop();

方法2:lastIndexOf + slice

定位最后一个/的位置后截取:

const path = '/api/media-objects/e78c7cfa-e469-4edd-8a87-9517a5b9e5da';
const slashIndex = path.lastIndexOf('/');
const targetId = path.slice(slashIndex + 1);

Java

方法1:lastIndexOf + substring

String path = "/api/media-objects/e78c7cfa-e469-4edd-8a87-9517a5b9e5da";
int slashPos = path.lastIndexOf('/');
String targetId = path.substring(slashPos + 1);

方法2:分割数组取最后一位

String path = "/api/media-objects/e78c7cfa-e469-4edd-8a87-9517a5b9e5da";
String[] parts = path.split("/");
String targetId = parts[parts.length - 1];

以上方法都能适配ID动态变化的场景,无论路径前半段结构如何,只要ID始终在最后一个/之后就能正确提取。

内容的提问来源于stack exchange,提问作者Ani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 13:15:34