【问题标题】:Take every item in list that starts with x and put it in a new list - Rego将列表中以 x 开头的每个项目放入一个新列表中 - Rego
【发布时间】:2020-08-07 18:54:07
【问题描述】:

list := ["a:aqsdf", "a:asdf", "b:gfs", "b:sdf", "a:adfd", "b:asdfd"]

我希望新列表仅包含以“a”开头的项目:["a:aqsdf", "a:asdf", "a:adfd"]

我尝试过使用集合但没有成功。这在 python 中将是一件轻而易举的事,但我似乎无法理解 rego。我可以把它变成一个集合,但不知道如何挤进 if 语句(startswith(list[_], "a") == true)

【问题讨论】:

    标签: open-policy-agent rego


    【解决方案1】:

    一种方法是使用数组解析和 startswith 内置函数:

    [ x | x := list[_]; startswith(x, "a")]
    

    游乐场示例:https://play.openpolicyagent.org/p/8mQYYvUL2h

    这实质上是说如果规则主体为真,则定义一个包含x 值的新数组。理解的规则体依次迭代 list 的所有索引以获取 x 的值,并且当 x 的值以 "a" 开头时为真。

    参考资料:

    【讨论】:

    • 如果我们想要所有以 'a' 或 'b' 开头的东西,除了使用 regex.match 还有其他选择吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 2017-07-10
    • 1970-01-01
    • 2022-11-07
    • 2019-10-10
    相关资源
    最近更新 更多