简体   繁体   English

用于从 AWS ARN 中提取区域名称的正则表达式

[英]Regex for extracting the region name from an AWS ARN

I'm trying to build a RegEx that extracts the region (us-east-1) from the following AWS ARN:我正在尝试构建一个从以下 AWS ARN 中提取区域 (us-east-1) 的 RegEx:

arn:aws:secretsmanager:us-east-1:123456789012:secret:catsndogs-3HieNb

I've tried using ([^:]*) which creates groups, but I can't seem to grab the value of the 4th group, ie us-east-1.我尝试使用创建组的([^:]*) ,但我似乎无法获取第 4 组的值,即 us-east-1。

(Since the OP did not specify a regex flavor, the following assumes PCRE; minor differences can arise if one changes the flavor; for instance, Golang uses $1 instead of \1 to refer to the first capturing group.) (由于 OP 没有指定正则表达式风格,以下假设为 PCRE;如果改变风格,可能会出现细微差异;例如,Golang 使用$1而不是\1来引用第一个捕获组。)

^(?:[^:]+:){3}([^:]+).*

Regex101正则表达式101

  • ^ is to start matching at the beginning of the line ^是从行首开始匹配
  • (?:[^:]+:){3} matches 3 repetitions of (?:[^:]+:) , which is a non-capturing group containing the regex [^:]+: , which matches a sequence of 1 or more non : followed by a : ; (?:[^:]+:){3}匹配 3 次重复(?:[^:]+:) ,这是一个包含正则表达式[^:]+:的非捕获组,它匹配一个序列1 个或多个非:后跟一个: ;
  • ([^:]+) matches and captures the 4th occurrence of that pattern ([^:]+)匹配并捕获该模式的第 4 次出现
  • .* matches all the rest of the line .*匹配该行的所有 rest

If the substitution expression is \1 , all the line will be substituted by the 4th : -separated field.如果替换表达式是\1 ,则所有行都将被第 4 个: -separated 字段替换。

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

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