Search code examples
kdb

Replace elements in list not matching a sub-string in KDB Q


How would I iterate through a list in KDB Q and replace elements which do not match a certain sub-string criteria?

Logic Example Pseudocode:

list.stream()
    .forEach(x -> {
        if (x matches substring) :
            newList.add(x)
        else :
            newList.add("")
     })

Current List:

S: ("Lint"; "Stack"; "Linode"; "Overflow";"Linux")

The sub-string to match is "Li" here. As such, strings "Stack" and "Overflow" are replaced by empty Strings as they do not contain the sub-string.

Resultant List:

S: ("Lint"; ""; "Linode"; "";"Linux")

Solution

  • A couple of ways you could go about it. First iterating over each element using conditional evaluation like below:

    q){$[x like "Li*";x;" "]}each S
    "Lint"
    " "
    "Linode"
    " "
    "Linux"
    

    Or using an at apply like below:

    q)@[S;where not S like\: "Li*";:;" "]
    "Lint"
    " "
    "Linode"
    " "
    "Linux"