DavidM
DavidM

Reputation: 31

Regex match with capture groups

I need some help with regex capture groups.

In the string below, I need it to match only if "skynet" is in the string and need two capture groups, accountid to capture the 12 digit account # and role to capture everything after the dash before "skynet":

aws-123456789012-skynet-tenant-134-admin

I have the regex below, which is almost what I need, except I need the role to be "skynet-tenant-134-admin", not "-tenant-134-admin":

^(?:[^-]*-)(?<accountid>\d{12})(?:[^-]*-)(?<target>skynet)(?<role>.*)

The goal is to only match if "skynet" appears after the second dash and two capture groups containing accountid (123456789012) and role (skynet-tenant-134-admin)

Upvotes: 1

Views: 101

Answers (1)

The fourth bird
The fourth bird

Reputation: 163597

You could nest the capturing groups and put target inside role

^(?:[^-]*-)(?<accountid>\d{12})(?:[^-]*-)(?<role>(?<target>skynet).*)

See a regex demo

Which you might shorten to without the use of the non capturing groups (?:

^[^-]*-(?<accountid>\d{12})[^-]*-(?<role>(?<target>skynet).*)

Upvotes: 1

Related Questions