java – Need regex to match word bounded by / or end of string

I need a regular expression to parse out the companyid and branchid in a url.

The issue is that the branchid may occur at the end of the string or it may occur in the middle of the string. it will always follow /branches.

Here are 2 examples:

http://localhost:8080/customer-api/customers/1128952/branches/83370
http://localhost:8080/customer-api/customers/1128952/branches/83370/validate

where 1128952 is the customerid and 83370 is the branchid

Now I know that

^.*customers/(.*?)/branches/(.*?)$ 

parses out the customerid and branchid for the first example and

^.*customers/(.*?)/branches/(.*?)/.*$

parses out the customerid and branchid for the second example

My problem is I want one regex to parse out the branchid that covers both cases. Can anyone help?

Read more here: Source link