3

I'm trying to build a RegEx that extracts the region (us-east-1) from the following AWS ARN:

arn:aws:secretsmanager:us-east-1:123456789012:secret:catsndogs-3HieNb

I've tried using ([^:]*) which creates groups, but I can't seem to grab the value of the 4th group, i.e. us-east-1.

1
  • If, as in the example, the desired between-colons text, and no undesired between-colons text, is always follows by a colon, one or more digits and another colon, you could use a positive lookahead: [^:]*(?=:\d+:). Commented May 12, 2020 at 20:35

1 Answer 1

3

(Since the OP did not specify a regex flavor, the following assumes PCRE; minor differences can arise if one changes the flavor; for instance, Golang uses $1 instead of \1 to refer to the first capturing group.)

^(?:[^:]+:){3}([^:]+).*

Regex101

  • ^ is to start matching at the beginning of the line
  • (?:[^:]+:){3} matches 3 repetitions of (?:[^:]+:), which is a non-capturing group containing the regex [^:]+:, which matches a sequence of 1 or more non : followed by a :;
  • ([^:]+) matches and captures the 4th occurrence of that pattern
  • .* matches all the rest of the line

If the substitution expression is \1, all the line will be substituted by the 4th :-separated field.

5
  • cannot get this to work - tried with grep and it always returns the entire arn: arn="arn:aws:lambda:eu-west-2:12345678912:layer:my-awsome-layer:3" grep -oP '^(?:[^:]+:){3}([^:]+).*' <<< "$arn" output: arn:aws:lambda:eu-west-2:12345678912:layer:my-awsome-layer:3
    – Kappacake
    Commented Nov 23, 2022 at 14:34
  • @Kappacake, have you read the disclaimer in the first paragraph?
    – Enlico
    Commented Nov 23, 2022 at 15:12
  • Yes, you are assuming PCRE (unless I missed something). Unfortunately that doesn't help me in figuring out what's wrong with my command or what the entire command should be.
    – Kappacake
    Commented Nov 23, 2022 at 15:13
  • 1
    Found a much simpler solution: echo "$arn" | cut -d':' -f4
    – Kappacake
    Commented Nov 23, 2022 at 15:14
  • @Kappacake, yeah, regex are not necessarily the best tool to solve any problem.
    – Enlico
    Commented Nov 23, 2022 at 15:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.