英文:
Alternative to negative look ahead
问题
我正在编写一个 Terraform 模块,需要捕获和替换字符串中的标记。这些标记被 {{...}}
包围,但我不想捕获与 {{global-...}}
匹配的标记。
例如:
locals {
input = "Hello {{name}} this is {{global-env}}. Welcome to {{home}}."
output = replace(local.input, "/{{(.+?)}}/", "{{$1-en_US}}")
}
output "output" { value = local.output }
# 实际输出: Hello {{name-en_US}} this is {{global-env-en_US}}. Welcome to {{home-en_US}}
# 期望输出: Hello {{name-en_US}} this is {{global-env}}. Welcome to {{home-en_US}}
在 C# 的正则表达式中,我可以使用负向前瞻:
{{(?!global-)(.+?)}}
然而,由于 Terraform 及其底层的 Go 语言运行时不支持前瞻,那么有什么替代方案呢?由于我在 Terraform 模块中,无法迭代每个匹配项并测试捕获组。
英文:
I am writing a Terraform module where I need to capture and replace tokens in strings. The tokens are enclosed by {{...}}
but I do not want to capture those that match {{global-...}}
.
For example:
locals {
input = "Hello {{name}} this is {{global-env}}. Welcome to {{home}}."
output = replace(local.input, "/{{(.+?)}}/", "{{$1-en_US}}")
}
output "output" { value = local.output }
# Actual: Hello {{name-en_US}} this is {{global-env-en_US}}. Welcome to {{home-en_US}}
# Expected: Hello {{name-en_US}} this is {{global-env}}. Welcome to {{home-en_US}}
In C# Regex, I could have used a negative look ahead:
{{(?!global-)(.+?)}}
However, since Terraform and its underlying Go lang runtime do not support lookarounds, what is the alternative? Being inside a Terraform module does not allow me to iterate over each match and test the capture group either.
答案1
得分: 1
你可以通过使用第二个替换来解决这个问题,将以 global-
开头并以 -en_US
结尾的占位符中的 -en_US
移除:
output = replace(replace(local.input, "/{{(.+?)}}/", "{{$1-en_US}}"), "({{global-.+?)-en_US}}", "$1}}")
英文:
You can work around it by using a second replacement to remove -en_US
from placeholders that start with global-
and end with -en_US
after the first replacement:
output = replace(replace(local.input, "/{{(.+?)}}/", "{{$1-en_US}}"), "({{global-.+?)-en_US}}", "$1}}")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论