简体   繁体   中英

Take every item in list that starts with x and put it in a new list - Rego

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

I want the new list to only include items that start with 'a': ["a:aqsdf", "a:asdf", "a:adfd"]

I've tried working with sets with no success. This would be a breeze in python but can't seem to wrap my head around rego. I can turn it into a set but not sure how to squeeze in an if statement(startswith(list[_], "a") == true)

One way to do this is with an array comprehension and the startswith builtin function:

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

Playground example: https://play.openpolicyagent.org/p/8mQYYvUL2h

This is essentially saying to define a new array containing the value of x if the rule body is true. The rule body for the comprehension is in turn iterating over all indicies of list for values of x , and will be true when the value of x starts with "a" .

References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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