4
$\begingroup$

KeyReplace is a user added function that can be used to replace keys in associations.

From the documentation:

KeyReplace[<|"a" -> 1, "b" -> 2|>, "a" -> "AA"]

However, the function requires you to specifically define the association key in order to replace it. What happens, for instance, if you have this situation:

KeyReplace[<|"key+(gibberish)" -> 1, "b" -> 2|>, "key+(gibberish)" -> "key"]

In this case, 'gibberish' would be characters that you may not be able to access from the keyboard. This seems to happen when SemanticImport is used with some types of files where the column names have symbols, like a degree sign, that you can't directly address with a keyboard.

I recognize one option is to simply go fix the header row and remove the problem characters in the application that generated the file. If I can't edit it, however, I'm stuck.

So...is there way to use pattern matching to address the problem? For instance, in the example above, is there a way to create a pattern and replacement that only uses the first three letters of the key as a match...since I really don't care what comes after it. This would allow me to skip the problem of explicitly defining what "(gibberish)" is and be able to strip it out with a replcement.

TIA

twd

$\endgroup$

1 Answer 1

5
$\begingroup$

When you have a function that matches ordinary Wolfram Language expressions but you want to match it as a string pattern, you can use PatternTest or Condition:

In[11]:= ResourceFunction["KeyReplace"][
    <|"key4323543" -> 1, "b" -> 2|>,
    _String?(StringStartsQ["key"]) -> "key"
 ]

Out[11]= <|"key" -> 1, "b" -> 2|>

note the use of parentheses after the ? operator, it is necessary if the test function is more than just a symbol.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.