0
$\begingroup$

How do you express the computation that, given a list of regular expressions, perform a replacement until one of them is satisfied.

For instance:

keys = {"x_millisec", "y", "z_milliseconds", "w_somethingelse", "a_Millisecs"}
pattern = ... (* it defines the named group `prefix' *)

With[ {key = ..., value = ... }, 
  Which[ 
    StringMatchQ[ key, pattern, IgnoreCase -> True],
    StringReplace[ key, { 
      (* remove the suffix `_millisecs' *)
      pattern :> StringTake[ prefix, StringLength[prefix] - 1] 
    }, IgnoreCase -> True ] -> Quantity[ value, "Milliseconds"] , 
    ...
    True, key -> value] 
  ]
] & /@ keys

This performs the replacement for a single pattern. Now I have a list of patterns for different units, such as seconds, millisecs, microsecs, nanosecs. I would to like to test the same string, `key', against each of those pattern, until one of them is satisfied. Is there a simpler way to proceed rather than extending the above redundant code?

$\endgroup$
1
  • $\begingroup$ This is literally what SelectFirst was designed to do. $\endgroup$
    – b3m2a1
    Commented Apr 1, 2018 at 6:26

1 Answer 1

1
$\begingroup$

I think I've managed to reach at least a solution by using scan to iterate over the patterns and adapting an example for Perl users about the paper jam from the product documentation. The idea is to split the process in two steps. The first step only creates a list of functions to be applied independently on each attribute of the dataset :

// ... for each key ...
scan = Scan [ 
  Module[{pattern, unit, repl}, 
    pattern = #["pattern"];
    unit = #["unit"];
    repl = StringReplace[key, pattern :> prefix , IgnoreCase -> True];

    If[repl != key, Return[ Quantity[ #, unit] & ] ] 
  &, patterns] 
If[scan =!= Null, scan, Identity]

Afterwards, iterate over each column/attribute of the data set/matrix and apply on each component the related function:

rules = %
Do[  
  data[[All, i]] = rules[[i]] /@ data[[All, i]],
  {i, Length[rules]}
];
$\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.