Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2009

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: String substitution system

  • To: mathgroup at smc.vnet.net
  • Subject: [mg97393] Re: String substitution system
  • From: Raffy <raffy at mac.com>
  • Date: Thu, 12 Mar 2009 02:20:39 -0500 (EST)
  • References: <200903070738.CAA16935@smc.vnet.net> <gp081u$l3g$1@smc.vnet.net>

On Mar 11, 3:08 am, Hauke Reddmann <fc3a... at uni-hamburg.de> wrote:
> THX for the answers. While I'm at it anyway,
> is it still that easy when I need substitution rules
> with placeholders? E.g. XY->YZ for fixed X,Z
> but any string Y?
>
> --
> Hauke Reddmann <:-EX8    fc3a... at uni-hamburg.de
> Nur Schufte schuften - Genie genie=DFt.

In my above response, I don't think I understood your question
entirely, after looking at DrMajorBob's response.  So here is my code
again, adapted to handle branched replacements:

vAlphabet = {"A", "B", "C", "D"};
vWords = Map[StringJoin, Join @@ Table[Tuples[vAlphabet, i], {i, 7}]];
vRules = {"CC" -> "C", "DD" -> "D", "CA" -> "C", "AC" -> "C",
   "DB" -> "D", "BD" -> "D", "CDC" -> "C", "DCD" -> "D", "CBC" -> "C",
    "DAD" -> "D", "ABC" -> "DC", "CBA" -> "CD", "BAD" -> "CD",
   "DAB" -> "DC", "BAB" -> "ABA"};

explode[v_List, s_String] := Block[
   {vFragments, vLength},
   vFragments =
    FixedPoint[Union@Flatten@{StringReplaceList[#, v], #} &, {s}];
   vLength = StringLength /@ vFragments;
   Pick[vFragments, vLength, Min[vLength]]
   ];

# -> explode[vRules, #] & /@ vWords

Which will a result like: "AABABBA" -> {"AAAABAA", "AAABABA",
"AABABBA"}
(in the case of multiple, equal length results)

Now, for your second question: you would want to create rules of the
form: "X"~~x_ :> x<>"Y"

I wrote a little function to create these results automatically:

smartRule[sBefore_String -> sAfter_String] := Block[
  {vBefore, vAfter, map},
  map[s_] := Throw["Unable to fill slot: ", s];
  vBefore = Characters[sBefore] /. x_String /; StringMatchQ[x,
DigitCharacter] :>
      ReleaseHold@Pattern[Evaluate[map[x] = ToExpression["Hold[x" <> x
<> "]"]], _];
  vAfter = Characters[sAfter] /. x_String /; StringMatchQ[x,
DigitCharacter] :> map[x];
  ReleaseHold@ReplacePart[RuleDelayed[StringExpression @@ vBefore,
Evaluate[vAfter]], {2, 0} -> StringJoin]
];

Which will do:

smartRule["X1" -> "1Y"]: "X" ~~ x1_ :> x1 <> "Y"
smartRule["X12" -> "1Y2"]: "X" ~~ x1_ ~~ x2_ :> x1 <> "Y" <> x2
smartRule["X11" -> "1Y1"]: "X" ~~ x1_ ~~ x1_ :> x1 <> "Y" <> x1

explode[{smartRule["A11" -> "1B"], "TB" -> "A"}, "ATT"] => {"A"}


  • Prev by Date: Re: Bug in Pattern Matching with Condition?
  • Next by Date: Notebooks that auto-execute when opened? -- SOLVED (I think)
  • Previous by thread: Re: String substitution system
  • Next by thread: Re: String substitution system