Dmitry Gusev
Dmitry Gusev

Reputation: 891

Regex to match URL path segments not containing a symbol

Given URL that may contain zero or many "ID-segments" (a segment that contains _ character), i.e.:

/v1/customer/cus_id/cards/card_id

what would be a regex that can find & replace all these segments with predefined string ([^/]+ in my case), so that end result would look like this:

/v1/customer/[^/]+/cards/[^/]+

Upvotes: 1

Views: 299

Answers (2)

Imu Sama
Imu Sama

Reputation: 364

This could work [^/]+_[^/]+ Well at least it worked with your example. What I did :

String x = "/v1/customer/cus_id/cards/card_id";
System.out.println(x.replaceAll("[^/]+_[^/]+","[^/]+"));

Upvotes: 2

glee8e
glee8e

Reputation: 6419

Replace every occurrence of [^/]+_[^/] with your string and you are good to go, provided every "ID-segments" all contain "", and segments that are not "ID-segments" will not contain ""

Upvotes: 1

Related Questions