Use servicePattern to extract groups and routePattern to construct the route.

If there is no matches, the serviceId is returned.
@param serviceId service discovered name
@return route path
427136
@Override
	public String apply(String serviceId) {
		Matcher matcher = this.servicePattern.matcher(serviceId);
		String route = matcher.replaceFirst(this.routePattern);
		route = cleanRoute(route);
		return (StringUtils.hasText(route) ? route : serviceId);
	}
365103
@Override
    @Path("/{requestId}")
    @ApiOperation(value="Retrieve a request or a page of requests according to specified filters",
        notes="If requestId is not present, returns all matching requests.",
        response=Request.class, responseContainer="List")
    public JSONObject get(String path, Map<String,String> headers)
    throws ServiceException, JSONException {
        RequestServices requestServices = ServiceLocator.getRequestServices();
        try {
            Query query = getQuery(path, headers);
            String segOne = getSegment(path, 1);
            if (segOne != null) {
                if (segOne.equals("tops")) {
                    return getTops(query).getJson();
                }
                else if (segOne.equals("breakdown")) {
                    return getBreakdown(query).getJson();
                }
                else if (segOne.equals("paths")) {
                    return getPaths(query).getJson();
                }
                else if (segOne.equals("insights")) {
                    JsonList<Insight> jsonList = getInsights(query);
                    JSONObject json = jsonList.getJson();
                    String trend = query.getFilter("trend");
                    if ("completionTime".equals(trend)) {
                        List<Timepoint> timepoints = requestServices.getRequestTrend(query);
                        json.put("trend", new JsonList<>(timepoints, "trend").getJson().getJSONArray("trend"));
                    }
                    return json;
                }
                else {
                    try {
                        if (query.getBooleanFilter("master")) {
                            String masterRequestId = segOne;
                            if (query.getBooleanFilter("response")) {
                                Request masterRequest = requestServices.getMasterRequestResponse(masterRequestId);
                                if (masterRequest == null)
                                    throw new ServiceException(ServiceException.NOT_FOUND, "Master request not found: " + masterRequestId);
                                return masterRequest.getJson();
                            }
                            else {
                                Request masterRequest = requestServices.getMasterRequest(masterRequestId);
                                if (masterRequest == null)
                                    throw new ServiceException(ServiceException.NOT_FOUND, "Master request not found: " + masterRequestId);
                                return masterRequest.getJson();
                            }
                        }
                        else {
                            Long requestId = Long.valueOf(segOne);
                            if (query.getBooleanFilter("request") && query.getBooleanFilter("response")) {
                                Request request = requestServices.getRequestAndResponse(requestId);
                                if (request == null)
                                    throw new ServiceException(ServiceException.NOT_FOUND, "Request not found: " + requestId);
                                return request.getJson();
                            }
                            else if (query.getBooleanFilter("response")) {
                                Request request = requestServices.getRequestResponse(requestId);
                                if (request == null)
                                    throw new ServiceException(ServiceException.NOT_FOUND, "Request not found: " + requestId);
                                return request.getJson();
                            }
                            else {
                                Request request = requestServices.getRequest(requestId);
                                if (request == null)
                                    throw new ServiceException(ServiceException.NOT_FOUND, "Request not found: " + requestId);
                                return request.getJson();
                            }
                        }
                    }
                    catch (NumberFormatException ex) {
                        throw new ServiceException(ServiceException.BAD_REQUEST, "Bad requestId: " + segOne);
                    }
                }
            }
            else {
                if (query.getLongFilter("ownerId") >= 0L) {
                    RequestList reqList = requestServices.getRequests(query);
                    if (!reqList.getItems().isEmpty())
                        return requestServices.getRequestAndResponse(reqList.getItems().get(0).getId()).getJson();
                    else
                        throw new ServiceException(ServiceException.NOT_FOUND, "Request not found for ownerId: " + query.getLongFilter("ownerId"));
                }
                else
                    return requestServices.getRequests(query).getJson();
            }
        }
        catch (ServiceException ex) {
            throw ex;
        }
        catch (Exception ex) {
            throw new ServiceException(ServiceException.INTERNAL_ERROR, ex.getMessage(), ex);
        }
    }
1177189
def service_endpoint url
      endpoint = LIST.find do |(pattern, endpoint)|
        url =~ pattern
      end
      endpoint ? endpoint.last : false
    end
1246611
protected SamlRegisteredService verifySamlRegisteredService(final String serviceId) {
        if (StringUtils.isBlank(serviceId)) {
            throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE,
                "Could not verify/locate SAML registered service since no serviceId is provided");
        }
        LOGGER.debug("Checking service access in CAS service registry for [{}]", serviceId);
        val registeredService =
            samlProfileHandlerConfigurationContext.getServicesManager()
                .findServiceBy(samlProfileHandlerConfigurationContext.getWebApplicationServiceFactory().createService(serviceId));
        if (registeredService == null || !registeredService.getAccessStrategy().isServiceAccessAllowed()) {
            LOGGER.warn("[{}] is not found in the registry or service access is denied. Ensure service is registered in service registry", serviceId);
            throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE);
        }

        if (registeredService instanceof SamlRegisteredService) {
            val samlRegisteredService = (SamlRegisteredService) registeredService;
            LOGGER.debug("Located SAML service in the registry as [{}] with the metadata location of [{}]",
                samlRegisteredService.getServiceId(), samlRegisteredService.getMetadataLocation());
            return samlRegisteredService;
        }
        LOGGER.error("CAS has found a match for service [{}] in registry but the match is not defined as a SAML service", serviceId);
        throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE);
    }
570651
public ServiceInstanceEntity get(final String serviceId)
	{
		try
		{
			return serviceCache.get(serviceId, () -> dao.getById(serviceId));
		}
		catch (Exception e)
		{
			throw new RuntimeException("Error loading service: " + serviceId, e);
		}
	}
211677
public static servicegroup get(nitro_service service, String servicegroupname) throws Exception{
		servicegroup obj = new servicegroup();
		obj.set_servicegroupname(servicegroupname);
		servicegroup response = (servicegroup) obj.get_resource(service);
		return response;
	}
581665
public void deleteService(String serviceId) {

        DeleteServiceRequest deleteServiceRequest = new DeleteServiceRequest().withId(serviceId);
        getDiscoveryClient().deleteService(deleteServiceRequest);

    }
1168121
@CheckForNull
    public String extractJvmRoute( @Nonnull final String sessionId ) {
        final int idxDot = sessionId.indexOf( '.' );
        return idxDot < 0 ? null : sessionId.substring( idxDot + 1 );
    }
905846
def factory(self, request, parent=None, name=None):
        
        traverse = request.matchdict['traverse']

        # show documentation at the root path
        if not traverse:
            return {}
        else:
            service = {}
            name = name or traverse[0]

            # look for direct pattern matches
            traversed = '/' + '/'.join(traverse)
            service_type = None
            service_object = None

            for route, endpoint in self.routes:
                result = route.match(traversed)
                if result is not None:
                    request.matchdict = result
                    request.endpoint = endpoint
                    break
            else:
                try:
                    service_type, service_object = self.services[name]
                except KeyError:
                    raise HTTPNotFound()

            if service_type:
                if isinstance(service_type, Endpoint):
                    service[name] = service_type
                elif service_object is None:
                    service[name] = service_type(request)
                else:
                    service[name] = service_type(request, service_object)

            request.api_service = service
            return service
463244
private List<ServiceInformation> getServiceInformations(URI location, final Map<String, String> params)
            throws IOException {
        final ReadOnlyDiscoveryClient discoveryClient = getDiscoveryClient(params);

        final String serviceType = params.get("serviceType");

        final List<ServiceInformation> services;

        if (serviceType != null) {
            services = discoveryClient.findAllServiceInformation(location.getHost(), serviceType);
        } else {
            services = discoveryClient.findAllServiceInformation(location.getHost());
        }
        return services;
    }
988307
public static <I extends Request, O extends Response>
    CompositeServiceEntry<I, O> of(String pathPattern, Service<I, O> service) {
        return new CompositeServiceEntry<>(PathMapping.of(pathPattern), service);
    }
1287196
static String normalizeServicePath(String servicePath) {
    Preconditions.checkNotNull(servicePath, "service path cannot be null");
    if (servicePath.length() == 1) {
      Preconditions.checkArgument(
          "/".equals(servicePath), "service path must equal \"/\" if it is of length 1.");
      servicePath = "";
    } else if (servicePath.length() > 0) {
      if (!servicePath.endsWith("/")) {
        servicePath += "/";
      }
      if (servicePath.startsWith("/")) {
        servicePath = servicePath.substring(1);
      }
    }
    return servicePath;
  }
512544
public static String parentRelativePathFromResourceId(String id) {
        if (id == null) {
            return null;
        }

        ResourceId parent = ResourceId.fromString(id).parent();
        if (parent != null) {
            return parent.resourceType() + "/" + parent.name();
        }

        return "";
    }
967858
public static function getRouteOptions($service, $serviceConfig, array $parameters = [], $useIdPattern = false)
    {
        if ($useIdPattern) {
            $parameters['id'] = self::ID_PATTERN;
        }
        return self::getRoute($service, 'OPTIONS', 'optionsAction', $serviceConfig, $parameters);
    }
431814
private static String cleanODataPath(String path, HandleParametersOption handleParameters) {
		String cleanedPath = path;
		
		if (HandleParametersOption.USE_ALL.equals(handleParameters) ) {
			cleanedPath = path;
		} else {

			// check for single ID (unnamed)
			Matcher matcher = patternResourceIdentifierUnquoted.matcher(path);
			if (matcher.find()) {
				String resourceName =  matcher.group(1); 
				String resourceID   =  matcher.group(2);
			
				String subString = resourceName + "(" + resourceID + ")";
				int begin = path.indexOf(subString);
				int end   = begin + subString.length();
				
				String beforeSubstring = path.substring(0,begin);
				String afterSubstring  = path.substring(end);
				
	
				if (HandleParametersOption.IGNORE_COMPLETELY.equals(handleParameters) ||
				    HandleParametersOption.IGNORE_VALUE.equals(handleParameters)	     ) {
					
					StringBuilder sb = new StringBuilder(beforeSubstring);
					sb.append(resourceName).append("()").append(afterSubstring);
					cleanedPath = sb.toString();
				} 
							
			} else {
				
				matcher = patternResourceMultipleIdentifier.matcher(path);
				if (matcher.find()) {
					// We've found a composite identifier. i.e: /Resource(field1=a,field2=3)
					
					String multipleIdentifierSection =   matcher.group(1); 
					
					int begin = path.indexOf(multipleIdentifierSection);
					int end   = begin + multipleIdentifierSection.length();
	
					String beforeSubstring = path.substring(0,begin);
					String afterSubstring  = path.substring(end);

					if (HandleParametersOption.IGNORE_COMPLETELY.equals(handleParameters) ) {
							cleanedPath = beforeSubstring + afterSubstring;
					} else {
						StringBuilder sb = new StringBuilder(beforeSubstring);
						
						matcher = patternResourceMultipleIdentifierDetail.matcher(multipleIdentifierSection);
						int i = 1;
						while (matcher.find()) {
							
							if (i >  1) {
								sb.append(',');
							}
							String paramName       = matcher.group(1);
							sb.append(paramName);
							i++;
						}
					
						sb.append(afterSubstring);
						cleanedPath = sb.toString();
					}
							
				} 
			}		
		}
		
		return cleanedPath;
	}
61607
def route_path(self, path):
        '''
        
        '''
        path = path.strip('/')
        name, _, subpath = path.partition('/')
        for service in singletons.settings.load_all('SERVICES'):
            if service.SERVICE_NAME == name:  # Found service!
                break
        else:
            return [], None  # found no service

        for partial_url, view in service.urls.items():
            partial_url = partial_url.strip('/')
            if isinstance(view, str):
                view = getattr(service, view)
            regexp = re.sub(r'<[^>]+>', r'([^/]+)', partial_url)
            matches = re.findall('^%s$' % regexp, subpath)
            if matches:
                if '(' not in regexp:
                    matches = []
                return matches, view

        return [], None
1308085
public static Artifact withGroupId(String groupId)
    {

        Artifact artifact = new Artifact();
        artifact.groupId = new RegexParameterizedPatternParser(groupId);
        return artifact;
    }