Home > Enterprise >  Regex to match an aws arn
Regex to match an aws arn

Time:01-17

I am trying to validate aws arn for a connect instance but I am stuck on creating the correct regex.

Below is the string that I want to validate.

arn:aws:connect:us-west-2:123456789011:instance/0533yu22-d4cb-410a-81da-6c9hjhjucec4b9

I want to create a regex which checks below things.

arn:aws:connect:<region_name>:<12 digit account id>:instance/<an alphanumeric instance id>

Can someone please help.

Tried below

^arn:aws:connect:\S :\d :instance\/\S \/queue\/\S $

CodePudding user response:

You need some capture groups to facilitate this. Here I've also used named capture groups for ease of understanding.

const string = "arn:aws:connect:us-west-2:123456789011:instance/0533yu22-d4cb-410a-81da-6c9hjhjucec4b9";

// Regex broken down into parts
const parts = [
  'arn:aws:connect:',
  '(?<region_name>[^:] ?)',         // group 1
  ':',
  '(?<account_id>\\d{12})',         // group 2
  ':instance\\/',
  '(?<instance_id>[A-z0-9\\-] ?)',  // group 3
  '$'
];

// Joined parts into regex expression
const regex = new RegExp(parts.join(''));

// Execute query and assign group values to variables
const { region_name, account_id, instance_id } = regex.exec(string).groups;

console.log("region_name:", region_name);
console.log("account_id:", account_id);
console.log("instance_id:", instance_id);

CodePudding user response:

There is no /queue/ substring in your example string, and \S matches any no whitespace character and will cause backtracking to match the rest of the pattern.

You might update your pattern to ^arn:aws:connect:\S :\d :instance\/\S $ but that will be less precise according to the things you want to check.

A bit more precise pattern could be:

^arn:aws:connect:\w (?:-\w ) :\d{12}:instance\/[A-Za-z0-9] (?:-[A-Za-z0-9] ) $
  • ^ Start of string
  • arn:aws:connect: Match literally
  • \w (?:-\w ) : Match 1 word characters and repeat matching - and 1 word characters and then match :
  • \d{12}: Match 12 digits and :
  • instance\/ Match instance/
  • [A-Za-z0-9] (?:-[A-Za-z0-9] ) Match 1 alpha numerics and repeat 1 times - and 1 alpha numerics
  • $ End of string

Regex demo

  •  Tags:  
  • Related