如何在Terraform中提取特定格式字符串中的客户名称?
问题描述
现有多个格式如下的字符串:
my-bucket-customer-staging-ie-app-data my-bucket-customer2-longname-prod-uk-app-data
需要从中提取客户名称,期望结果分别为customer、customer2-longname。
试过用trimprefix移除固定前缀my-bucket-,但后缀的环境/区域部分不固定,没法用trimsuffix。本来想通过截取字符串忽略最后4个元素来提取客户名,但这个方法对带连字符的长客户名不管用,而且写起来麻烦,想找更简单的解决办法。
解决方案
Shell(Bash)实现
先去掉固定前缀,再把剩余字符串按连字符拆成数组,剔除最后4个后缀相关的元素,最后把剩下的部分用连字符拼接回来就行:
# 定义提取函数 extract_customer() { # 移除前缀 local trimmed=${1#my-bucket-} # 按连字符分割成数组 local parts=(${trimmed//-/ }) # 取数组中除最后4个元素外的部分 local customer_parts=("${parts[@]:0:${#parts[@]}-4}") # 把数组元素用连字符拼接 echo "${customer_parts[*]}" | tr ' ' '-' } # 测试示例 str1="my-bucket-customer-staging-ie-app-data" str2="my-bucket-customer2-longname-prod-uk-app-data" extract_customer "$str1" # 输出 customer extract_customer "$str2" # 输出 customer2-longname
Python实现
用Python的话写法更简洁,思路一样:移除前缀后分割成列表,切片去掉最后4个元素再拼接:
def extract_customer(s): # 移除固定前缀 trimmed = s.removeprefix("my-bucket-") # 按连字符分割 parts = trimmed.split("-") # 取除最后4个元素外的部分并拼接 return "-".join(parts[:-4]) # 测试 print(extract_customer("my-bucket-customer-staging-ie-app-data")) # 输出 customer print(extract_customer("my-bucket-customer2-longname-prod-uk-app-data")) # 输出 customer2-longname
内容的提问来源于stack exchange,提问作者davo777
相关产品推荐
相关产品推荐

