0

Hi I am new to tcl and want to assign "\n" to a variable and use that variable in regsub to replace that string. It should be like :

set a "\n\[\"this is my code\"\]"
puts $a

I was expecting this will give \n\[\"this is my code\"\], then I could use this $a in regsub {$a} $str "replace" sub_str. This regsub could search $a inside $str and replace the matching one with replace and strore it in sub_str. However, it gave me [this is my code] Is there a way I could get the 1st format as \n\[\"this is my code\"\] so I could use that to do the string regsub?

Thanks!

Shang
  • 17
  • 3
  • Backslashing the backslashes is always an option. If you're not doing variable or command substitutions, consider putting things in braces (as _no_ substitutions are done inside there; that's the _real_ meaning of braces in Tcl). – Donal Fellows Oct 15 '20 at 08:23

1 Answers1

2

Use braces instead of quotes to prevent evaluation of the backslash escapes:

set a {\n\[\"this is my code\"\]}
puts $a

prints

\n\[\"this is my code\"\]
Shawn
  • 47,241
  • 3
  • 26
  • 60
  • Hi Shawn, Thanks for your reply. This works for me. However, if I want do : set $b = "this is my code" and put $b into the set a <...$b...>. what would be the way to also evaluate the content of b as "this is my code"? – Shang Oct 15 '20 at 05:11
  • 2
    @Shang If I understand you right, something like `set b {"this is my code"}; set a [format {\n\[%s\]} $b]` is probably the cleanest way. – Shawn Oct 15 '20 at 05:20
  • yes, this is what I mean. Thanks, really appreciate it! – Shang Oct 15 '20 at 19:13