Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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})?$

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading