1
$\begingroup$

Wrote this code to change MS Access variant of SQL date format to T-SQL, basically recognize dates delimited with pounds and change pounds to single quotes

My Mathematica code is Pythonic, because I use a Do loop

How would you do it?

changeDateFormat01[s_String] := Block[
  {ss, pp},
  ss = s;
  Do[
    ss = StringReplacePart[ss, 
      "'" <> StringTake[ss, {pp[[1]] + 1, pp[[2]] - 1}] <> "'", pp],
   {pp, Reverse@
     StringPosition[ss, RegularExpression["\\#\\d+\\/\\d+\\/\\d+\\#"]]}
   ];
  ss
 ]

changeDateFormat01["hello#1/1/2013#hello#donotbefooled#1/1/2013hello#1/1/2013#hello"]

(* "hello'1/1/2013'hello#donotbefooled#1/1/2013hello'1/1/2013'hello" *)
$\endgroup$
  • $\begingroup$ We don't use SMS style in this forum. $\endgroup$ – user64494 May 18 at 5:25
1
$\begingroup$

Let

str1 = "hello#1/1/2013#hello#donotbefooled#1/1/2013hello#1/1/2013#hello";

then

StringReplace[str1, 
 "#" ~~ dt : (DigitCharacter.. ~~ "/" ~~ DigitCharacter.. ~~ "/" ~~ 
      DigitCharacter..) ~~ "#" :> "'" ~~ dt ~~ "'"]

produces

"hello'1/1/2013'hello#donotbefooled#1/1/2013hello'1/1/2013'hello"

without a loop in sight. Note that I've used Mathematica's own string expression syntax, but you could just as easily use regular expressions if you prefer.

I'll leave it to you to wrap the foregoing snippet into a function, that seems to be well within your grasp.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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