负向预查的替代方法

huangapple go评论87阅读模式
英文:

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}}")

huangapple
  • 本文由 发表于 2021年7月30日 09:41:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/68584497.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定