简体   繁体   中英

Get path variable from URL using RegEx

How do I get the customerid path variable from the following URL:

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

The customerid path variable can vary in length, so I want everything between /customers/ and /agreements...

I have searched the net for a solution and tried to construct some RegEx myself but so far unsuccesfully.

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

UPDATE: I just realized you were referring to Java, but the above solutions are still valid. 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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