Skip to main content
Tweeted twitter.com/StackMma/status/1049041774772215809
edited title
Link
brienna
  • 1.1k
  • 5
  • 13

ReplaceAll Replace targeted elements in first level of list only

Source Link
brienna
  • 1.1k
  • 5
  • 13

ReplaceAll in first level of list only

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?