如何从URI https://www.google.com/items/2中提取商品ID(2)用于后续处理
从URI中提取商品ID的方法
现有URI地址为https://www.google.com/items/2,需要从中提取出商品ID(即数值2)用于后续业务处理,以下是几种实用的实现方式:
方法一:字符串分割法
利用URI的路径结构,按/分割字符串后取最后一段即可,适合路径结构固定的场景:
Python示例
uri = "https://www.google.com/items/2" item_id = uri.split("/")[-1] print(item_id) # 输出:2
JavaScript示例
const uri = "https://www.google.com/items/2"; const itemId = uri.split("/").pop(); console.log(itemId); // 输出:2
方法二:正则表达式匹配
如果商品ID是纯数字,可用正则匹配最后一个/后的数字序列,兼容性更强:
Python示例
import re uri = "https://www.google.com/items/2" match_result = re.search(r"/(\d+)$", uri) if match_result: item_id = match_result.group(1) print(item_id) # 输出:2
JavaScript示例
const uri = "https://www.google.com/items/2"; const matchResult = uri.match(/\/(\d+)$/); if (matchResult) { const itemId = matchResult[1]; console.log(itemId); // 输出:2 }
方法三:URL解析API(规范方式)
利用语言自带的URL解析工具,先解析URI结构再提取路径段,适合复杂URI场景:
Python示例
from urllib.parse import urlparse uri = "https://www.google.com/items/2" parsed_uri = urlparse(uri) path_segments = parsed_uri.path.split("/") item_id = path_segments[-1] print(item_id) # 输出:2
JavaScript示例
const uri = "https://www.google.com/items/2"; const urlObj = new URL(uri); const pathSegments = urlObj.pathname.split("/"); const itemId = pathSegments.pop(); console.log(itemId); // 输出:2
内容的提问来源于stack exchange,提问作者HARIPRAKASH
相关产品推荐
相关产品推荐

