Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for EC2 instance ID

I need a regex that will be able to match AWS EC2 instance IDs. Instance IDs have the following criteria:

  • Can be either 8 or 17 characters
  • Should start with i-
  • Followed by either a-f or 0-9

Valid instance IDs are: i-ed3a2f7a or i-096e0bec99b504f82 or i-0cad9e810fbd12f4f

Invalid instance IDs are e123g12 or i-1fz5645m

I was able to create the following regex i-[a-f0-9](?:.{7}|.{16})$ but it is also accepting i-abcdeffh. h is not between a-f

Grateful if someone could help me out

like image 600
Mervin Hemaraju Avatar asked Apr 07 '26 06:04

Mervin Hemaraju


1 Answers

You can make a regex to match the 8-character ID value and add an optional 9 characters after it:

^i-[a-f0-9]{8}(?:[a-f0-9]{9})?$

This will match:

  • ^ : beginning of line
  • i- : the characters i-
  • [a-f0-9]{8} : 8 hex digits
  • (?:[a-f0-9]{9})? : an optional additional 9 hex digits
  • $ : end of line

Demo on regex101

Note we use start and end of line anchors to prevent matching additional characters before or after the ID value. This regex will match only 8 or 17 character ID values, not 12 or 11 or 5 etc.

like image 137
Nick Avatar answered Apr 10 '26 00:04

Nick