TCL regsub multiple special characters in one shot

1.6k Views Asked by At

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?

2

There are 2 best solutions below

0
glenn jackman On BEST ANSWER

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

0
Donal Fellows On

The general approach to use is to build a RE character set ([…]) and use that. You have to be a bit careful with those in some cases (some characters are special in them, especially ^, ], - and \), but it's not too difficult.

regsub -all {[][/{}]} $input {\\&}

However, if you can use character classes (such as \W or [^\w]) then it's a lot simpler and easier to read. Most common cases of needing to apply backslashes work with those.