Regex for extracting resource name from ARN

Viewed 17

I'm trying to create a regex to extract the resource name from all resources ARNs. There are these ARN structures:

arn:aws:service:region:accountnumber:resourcename
arn:aws:service:region:accountnumber:resourcetype/resourcename
arn:aws:service:region:accountnumber:resourcetype:resourcename

For these I've found this regex in regex101:

^arn:(?P<Partition>[^:\n]*):(?P<Service>[^:\n]*):(?P<Region>[^:\n]*):(?P<AccountID>[^:\n]*):(?P<Ignore>(?P<ResourceType>[^:\/\n]*)[:\/])?(?P<Resource>.*)$

But I've found out there's also a special case for load balancer where the above regex doesn't work. for example:

arn:aws:elasticloadbalancing:region:accountnumber:loadbalancer/net/resourcename/alphanumeric

The only solution I could find has 2 match groups and after using the regex I need to check if Group2 has a match, if not then to use Group1:

\:[^\/]*[\/\:]([^\/]+)$|([^\/]+)\/[^\/]+$

I'm trying to find a regex with a single group which will extract the resource name.

** For S3 (or any other resource), I don't need to support ARN + subfolder. only the S3 ARN.

1 Answers

If the part in the ignore can be preceded by a pattern like loadbalancer/net you might append an optional part in the Ignore group:

^arn:(?P<Partition>[^:\n]*):(?P<Service>[^:\n]*):(?P<Region>[^:\n]*):(?P<AccountID>[^:\n]*):(?P<Ignore>(?:[^\/\n]*\/[^\/\n]*)?(?P<ResourceType>[^:\/\n]*)[:\/])?(?P<Resource>.*)$

Regex demo

Related