Home > Software engineering >  Extract value from event path - lambda function
Extract value from event path - lambda function

Time:08-30

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>>).

CodePudding user response:

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

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

enter image description here

CodePudding user response:

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.

  • Related