I want to use one regex to extract the aws account id for two types of format
arn:aws:ec2:us-west-2:1234567890:instance/i-0a89fdbedc3f1d76a
arn:aws:iam::1234567890:instance-profile/aws-elasticbeanstalk-ec2-role
I.e., the regex should be able to match 1234567890
in both lines.
I know how to create regex for each format, but want to have one single regex if possible.
CodePudding user response:
I'd use the following regexp: arn:aws:(?:ec2|iam):[^:]*:([0-9] ):
The prefix is arn:aws:
, followed by either ec2
or iam
and one may-be-empty segment. After the prefix there must be a non-empty group of digits. It is exactly the group with the instance number.
Example https://go.dev/play/p/mP6VyIYa3v_N
CodePudding user response:
Dont need RegExp, just pick out the fifth column:
package aws
import (
"strconv"
"strings"
)
func extract(s string) (int, error) {
split := strings.SplitN(s, ":", 6)
return strconv.Atoi(split[4])
}