2
$\begingroup$

I have two lists as follow:

l = {"XY", "XT", "AB", "GT"};
ll = {{"x", "g", "f"}, {"x", "y", "l", "t"}, {"x", "c", "a", "b", 
    "z"}, {"g", "t"}};

for each element in l (i.e. l[[1]],l[[2]],l[[3]] and l[[4]]) I want to go through ll and if the character exist then I replace them with the corresponding element of l. For example: for l[[1]] in ll I should have:

{{"x", "g", "f"}, {"XY", "l", "t"}, {"x", "c", "a", "b", 
        "z"}, {"g", "t"}}

For l[[2]] there is

{{"x", "g", "f"}, {"XT", "y", "l"}, {"x", "c", "a", "b", 
        "z"}, {"g", "t"}};

for l[[3]] I get:

{{"x", "g", "f"}, {"x", "y", "l", "t"}, {"x", "c", "AB", 
        "z"}, {"g", "t"}}

and for l[[4]] I should get:

{{"x", "g", "f"}, {"x", "y", "l", "t"}, {"x", "c", "a", "b", 
        "z"}, {"GT"}}
$\endgroup$
2
$\begingroup$
replace = Replace[ll,{a___,##&@@ToLowerCase[Characters@#],b___}:>{a, #, b}, ∞]&;

replace[l[[3]]]

{{"x", "g", "f"}, {"x", "y", "l", "t"}, {"x", "c", "AB", "z"}, {"g",  "t"}}

replace /@ l // Column

enter image description here

Also, an alternative way to use SequenceReplace:

sr = SequenceReplace[{a__ /;(StringMatchQ[StringJoin@a , #, 
   IgnoreCase -> True])} :> #] /@ ll &;
sr /@ l === replace /@ l

True

$\endgroup$
  • $\begingroup$ thank you for the answer, I just edited my question which was my mistake. Is it possible to have this for orderless set? in which case replace[l[[2]]] should give: {{"x", "g", "f"}, {"XT", "y", "l"}, {"x", "c", "a", "b", "z"}, {"g", "t"}} $\endgroup$ – Wiliam Nov 6 '18 at 10:46
  • $\begingroup$ I did it using: replace = Replace[ll, {OrderlessPatternSequence[ a___, ## & @@ ToLowerCase[Characters@#], b___]} :> {a, #, b}, \[Infinity]] &; :) $\endgroup$ – Wiliam Nov 6 '18 at 10:51
  • $\begingroup$ I have added a more generalised version here mathematica.stackexchange.com/questions/185424/… but so far couldn't work it out $\endgroup$ – Wiliam Nov 7 '18 at 0:02
2
$\begingroup$
SequenceReplace[ToLowerCase@Characters[#] -> # & /@ l] /@ ll
{{"x", "g", "f"}, {"XY", "l", "t"}, {"x", "c", "AB", "z"}, {"GT"}}
$\endgroup$
  • $\begingroup$ Thanks @Kuba but as I mentioned in my example I need separate lists for each of l[[1]], l[[2]], l[[3]] and l[[4]] $\endgroup$ – Wiliam Nov 5 '18 at 16:16

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.