简体   繁体   English

EC2 实例 ID 的正则表达式

[英]Regex for EC2 instance ID

I need a regex that will be able to match AWS EC2 instance IDs.我需要一个能够匹配 AWS EC2 实例 ID 的正则表达式。 Instance IDs have the following criteria:实例 ID 具有以下条件:

  • Can be either 8 or 17 characters可以是 8 或 17 个字符
  • Should start with i-应该以 i- 开头
  • Followed by either af or 0-9后跟 af 或 0-9

Valid instance IDs are: i-ed3a2f7a or i-096e0bec99b504f82 or i-0cad9e810fbd12f4f有效的实例 ID 为: i-ed3a2f7ai-096e0bec99b504f82i-0cad9e810fbd12f4f

Invalid instance IDs are e123g12 or i-1fz5645m无效的实例 ID 为e123g12i-1fz5645m

I was able to create the following regex i-[a-f0-9](?:.{7}|.{16})$ but it is also accepting i-abcdeffh .我能够创建以下正则表达式i-[a-f0-9](?:.{7}|.{16})$但它也接受i-abcdeffh h is not between af h不在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:您可以创建一个正则表达式来匹配 8 个字符的 ID 值,并在其后添加一个可选的 9 个字符:

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

Demo on regex101正则表达式 101 上的演示

Note we use start and end of line anchors to prevent matching additional characters before or after the ID value.请注意,我们使用行首锚点和行尾锚点来防止在 ID 值之前或之后匹配其他字符。 This regex will match only 8 or 17 character ID values, not 12 or 11 or 5 etc.此正则表达式将匹配 8 或 17 个字符 ID 值,而不是 12 或 11 或 5 等。

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-'; ^i- - 起始线锚点,后跟字面“i-”;
  • (?: - Open non-capture group for alternation; (?: - 打开非捕获组进行交替;
    • [af\d]{8} - Match 8 times any character from given character class; [af\d]{8} - 匹配给定字符 class 中任何字符的 8 次;
    • | - Or; - 或者;
    • [af\d]{17} - Match 17 times any character from given character class; [af\d]{17} - 匹配给定字符 class 中的任何字符 17 次;
  • $ - End-line anchor. $ - 结束线锚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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