Search code examples
tclregsub

TCL regsub multiple special characters in one shot


Is there a way to add escape '\' into a string with multiple special characters?

Example input : a/b[1]/c/d{3}
Desired outcome : a\/b\[1\]\/c\/d\{3\}

I've done it in multiple regsubs one special character at a time. But is there a way to do it in one shot?


Solution

  • I would simply escape all non-word characters:

    set input {a/b[1]/c/d{3}}
    set output [regsub -all {\W} $input {\\&}]
    puts $output
    
    a\/b\[1\]\/c\/d\{3\}
    

    ref: https://tcl.tk/man/tcl8.6/TclCmd/regsub.htm and https://tcl.tk/man/tcl8.6/TclCmd/re_syntax.htm