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
CodePudding user response:
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})?$
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.
CodePudding user response:
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;[a-f\d]{8}- Match 8 times any character from given character class;|- Or;[a-f\d]{17}- Match 17 times any character from given character class;
$- End-line anchor.
