简体   繁体   English

使用 RegEx 从 URL 获取路径变量

[英]Get path variable from URL using RegEx

How do I get the customerid path variable from the following URL:如何从以下 URL 获取 customerid 路径变量:

/customers/{customerid}/agreements/{agreementid} /customers/{customerid}/agreements/{agreementid}

The customerid path variable can vary in length, so I want everything between /customers/ and /agreements... customerid 路径变量的长度可以不同,所以我想要 /customers/ 和 /agreements 之间的所有内容...

I have searched the net for a solution and tried to construct some RegEx myself but so far unsuccesfully.我在网上搜索了一个解决方案,并尝试自己构建一些 RegEx,但到目前为止没有成功。

If you know the order of the elements in the URL is fixed (Ie there is nothing before the /customers segment, like a site/languages prefixes - /uk ), you can just split the URL and grab the 2nd element in the resulting array.如果您知道 URL 中元素的顺序是固定的(即/customers段之前没有任何内容,例如站点/语言前缀 - /uk ),则可以split URL 并获取结果数组中的第二个元素. Like so:像这样:

var urlParts = url.split('/');
var customerId = urlParts[1]; // Arrays positions start at 0.

Or more elegantly:或者更优雅:

var customerId = url.split('/')[1];

If you're not sure about the URL structure, but know that the customer ID is always right after the /customers segment, you can use regular expression to extract it.如果您不确定 URL 结构,但知道客户 ID 总是紧跟在/customers段之后,您可以使用正则表达式来提取它。

UPDATE: I just realized you were referring to Java, but the above solutions are still valid.更新:我刚刚意识到您指的是 Java,但上述解决方案仍然有效。 Here's a similar question about URL splitting in Java: In java, what's the best way to read a url and split it into its parts?这是有关 Java 中 URL 拆分的类似问题: 在 Java 中,读取 url 并将其拆分为各个部分的最佳方法是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM