Hbaecklund
Hbaecklund

Reputation: 279

How to regex last part of URL only?

I want to do a regex that target the end of a url:

www.company.com/orders/thanks

If you return from email or account page order ID is populated in the end:

www.company.com/orders/thanks/1sfasd523425

So I only want to target the URL that ends with /thanks

This thread bring is similiar: How do I get the last segment of URL using regular expressions

Had something similair .*\/thanks\/.+ but target incorrectly.

EDIT: Only target URLs ending with /thanks or /thanks/

Upvotes: 2

Views: 7243

Answers (2)

Ran Adler
Ran Adler

Reputation: 3711

Use URL object dont parse it yourself 

URL url = new URL("http://stackoverflow.com/questions/36616915/how-to-regex-last-part-of-url-only");
URLDecoder.decode(url.getPath(), "utf-8");
url.getPath();
url.getContent();
url.getPort();
url.getContent();

Upvotes: 0

user2705585
user2705585

Reputation:

Try with lookahead like this.

Regex: .+(?=\/thanks$).+

Explanation: This will match the URL only if thanks is at end of string by positive lookahead.

Regex101 Demo

Upvotes: 2

Related Questions