Regex to keep only portion of a URL

Viewed 43

I have a set of data looking like that:

/v2/ports/PF-12345
/v2/services/cloud/PF-12345
/v2/services/cloud/connections/PF-12345
/v2/services/cloud-routers/PF-L3-CUST-12345/connections
/v2/services/cloud-routers/PF-L3-CUST-12345678/connections/PF-L3-CON-12345678/bgp/c03664c5-fd8d-8623-acb5-bda4b545fb32
/v2.1/services/cloud-routers/PF-L3-CUST-12345/connections/PF-L3-CON-12345/status

I am trying to modify this data set like below (basically removing the version and the IDs/UUID in the URL).

ports
services/cloud
services/cloud/connections
services/cloud-routers/connections
services/cloud-routers/connections/bgp
services/cloud-routers/connections/status

I have been trying to figure out the right regular expression but can't get something working.

Here is a regular expression I worked on.

\/.*(?=\/.*?)

This is to use in Grafana to transform data just FYI.

1 Answers

With your shown samples only, please try following regex.

^\/[^\/]*\/(.*?)PF-[^\/]*\/(.*?)(?:PF-[^\/]*\/(?!PF-[^\/]*\/)(.*))?$

Here is the Online Demo for shown regex.

Explanation: Adding detailed explanation for above regex.

^\/[^\/]*\/       ##From starting of value matching / till next occurrence of / including / here.
(.*?)             ##Creating 1st capturing group where using lazy match(till next condition, explained below).
PF-[^\/]*\/       ##matching PF- till next occurrence of / including / here.
(.*?)             ##Creating 2nd capturing group where using lazy match(till next condition, explained below).
(?:               ##Creating a non-capturing group here.
  PF-[^\/]*\/     ##Matching PF- till next occurrence of / including / here.
  (?!PF-[^\/]*\/) ##Using negative look ahead to make sure its not preceded by PF- till next occurrence of / including / here.
  (.*)            ##Creating capturing group with greedy match here.
)?$               ##Closing non-capturing group and keeping it optional at the end of value here.
Related