5
$\begingroup$

I have a list where some elements are strings or sublists:

list = {"DTLCIGYHANNSTDT", "LCLGHHAVPNGTLVKTITNDQIEVTNATELVQSSSTGKI", \
"CLGHHAVPNGTLVKTITNDQIEVTNATELVQSSSTGKIC", {"H25", " H45", " I361", 
  " D362"}, "N197", {"H25", " H45", " S46", " V47", " T332", " V361", " D362",
   " G363", " W364", " Q381", " K382", " T384", " Q385", " I388", 
  " N389", " V395", " N396", " I399"}, {"H25", " H45", " V47", " N48",
   " L49", " T332", " D362", " G363", " W364", " Q381", " T384", 
  " Q385", " I388", " N389", " T392", " V395", " N396", " I399", 
  " E400"}, "NSTDTVDTVLEKNVT", {"D31", " S46"}, "S145", ... }

I want to target the 1st level strings that look like "N197" or "S145" and replace them with {N197} and {S145}. Transform from String to List, essentially.

I've tried with

list /. 
 x_String /; 
   StringMatchQ[x, RegularExpression["^[A-Z]\\d{1,3}$"]] :> List[x]

This command affects the desired elements, PLUS the first string element of every sublist. I know I'm missing something obvious, but how can I keep the changes to the 1st-level of the list?

$\endgroup$
7
$\begingroup$

Do not use ReplaceAll when you need a level spec. Use Replace. Avoid in general using ReplaceAll in favor of Replace in complex data structures unless you know for sure what is happening and what side-effects ReplaceAll can bring as you keep building your application and growing your code.

pattern = x_String /; StringMatchQ[x,RegularExpression["^[A-Z]\\d{1,3}$"]];

Replace[list, pattern :> List[x], {1}]
$\endgroup$
  • $\begingroup$ Thanks for the tip about ReplaceAll! $\endgroup$ – briennakh Oct 7 '18 at 20:32

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.