0

The lambda I am working on gets triggered through API gateway. I want to extract the a specific value from the path in the URL.

Sample URL : {id}/contacts

or

{id-0}/{id}/contacts

In order to extract the path variable I am using event.pathParamters which gives me the value, but I need to only extract {id} from the path.

I am using the following code to split the path param and extract the {id}, but this is not a feasible option:

arr = path.split("/");
id = arr[arr.length-2];

Are there better ways to extract {id}? The position of this id will be always last right before api name (in his case <<contacts>>).

2 Answers 2

1

This would extract the string which is located between the last two occurrences of / or the first occurrence if two / do not exist

([^\/]+)\/[^\/]+$

https://regex101.com/r/tZNhrk/1

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @ZygD. I think I can work with this expression.
0

Would you please try the following;

import re
str = '{id-0}/{id}/contacts'            # example
api_name = 'contacts'                   # api name
m = re.search(r'[^/]+(?=/%s)' % api_name, str)
if m:
    id = m.group()

The regex [^/]+(?=/%s) matches a string of non-slash characters which is followed by a slash and the specified api_name. If the regex matches, m.group() is assigned to it.

1 Comment

The problem here is that I don't know what the api_name would be.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.