简体   繁体   中英

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 af 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 af

Grateful if someone could help me out

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.

You seem to be able to just use:

^i-(?:[a-f\d]{8}|[a-f\d]{17})$

See an online demo


  • ^i- - Start-line anchor followed by literally 'i-';
  • (?: - Open non-capture group for alternation;
    • [af\d]{8} - Match 8 times any character from given character class;
    • | - Or;
    • [af\d]{17} - Match 17 times any character from given character class;
  • $ - End-line anchor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM