TransWikia.com

ReplaceAll not evaluating the rule delayed function

Mathematica Asked on May 5, 2021

Given

records = {<|"Material" -> "FG126", "Batch" -> "0000000009", "CreationDateTime" -> "/Date(1474502400000+0000)/"|>, 
<|"Material" -> "FG126","Batch" -> "0000000011", "CreationDateTime" -> "/Date(1474588800000+0000)/"|>};

records /. (a_String /; 
StringMatchQ[a, "/Date(" ~~ ___ ~~ "+0000)/"] :> StringTake[a, {7, 19}])

Returns

{<|"Material" -> "FG126", "Batch" -> "0000000009", 
  "CreationDateTime" -> 
   StringTake[
    "/Date(1474502400000+0000)/", {7, 19}]|>, <|"Material" -> "FG126",
   "Batch" -> "0000000011", 
  "CreationDateTime" -> 

Instead of

{<|"Material" -> "FG126", "Batch" -> "0000000009", "CreationDateTime" ->"1474502400000"|>, 
 <|"Material" -> "FG126", "Batch" -> "0000000011", "CreationDateTime" -> "1474588800000"|>}

The final desired outcome is actually to get the value at CreationDateTime processed as

FromUnixTime[creationDateTime/1000]

2 Answers

You can wrap rhs in lhs :> rhs with RuleCondition to force evaluation of the expression rhs:

records /. (a_String /; 
   StringMatchQ[a, "/Date(" ~~ ___ ~~ "+0000)/"] :> 
      RuleCondition[StringTake[a, {7, 19}]])
{<|"Material" -> "FG126", 
   "Batch" -> "0000000009", 
   "CreationDateTime" -> "1474502400000"|>,
<|"Material" -> "FG126", 
  "Batch" -> "0000000011", 
  "CreationDateTime" -> "1474588800000"|>}

Or use RuleCondition instead of Condition (/;):

records /. a_String :> 
  RuleCondition[StringTake[a, {7, 19}], StringMatchQ[a, "/Date(" ~~ ___ ~~ "+0000)/"] ]
{<|"Material" -> "FG126", 
   "Batch" -> "0000000009", 
   "CreationDateTime" -> "1474502400000"|>,
 <|"Material" -> "FG126",
   "Batch" -> "0000000011", 
   "CreationDateTime" -> "1474588800000"|>}

See also: The answers Replacement inside held expression.

Correct answer by kglr on May 5, 2021

It works if you take the data out of the association for the replacement.

Map[Association, Normal[records] /. (a_String /; StringMatchQ[a,
      "/Date(" ~~ ___ ~~ "+0000)/"] :> StringTake[a, {7, 19}])]
{<|"Material" -> "FG126", "Batch" -> "0000000009", 
  "CreationDateTime" -> "1474502400000"|>,
 <|"Material" -> "FG126", "Batch" -> "0000000011",
  "CreationDateTime" -> "1474588800000"|>}

Answered by Chris Degnen on May 5, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP