i am trying to replace all the special characters including white space, hyphen, etc, to underscore, from a string variable in tcl.
Example
input: Stack Overflow helps%me(a lot output: Stack_Overflow_helps_me_a_lot
I wrote the code below but it doesn’t seem to be working.
set varname $origVar
puts "Variable Name :>> $varname"
if {$varname != ""} {
regsub -all {[\s-\]\[$^?+*()|\\%&#]} $varname "_" $newVar
}
puts "New Variable :>> $newVar"
one issue is that, instead of replacing the string in $varname, it is deleting the data after first space encountered inside $origVar instead of $varname. Also there is no value stored in $newVar. No idea why, and also i read the example code (for proper syntax) in my tcl book and according to that it should be something like this
regsub -all {[\s-][$^?+*()|\\%&#]} $varname "_" newVar
so i used the same syntax but it didn’t work and gave the same result as modifying the $origVar instead of required $varname value.
The second version is closer. By putting the result in
$newVaryou’re actually setting a variable named whatever is stored in$newVar, i.e. you would then have to access it by$$newVar, so to speak (not valid in Tcl). Anyway, the issue is probably that in your second version, you don’t seem to be escaping certain characters. Try this:Another way to organize that to minimize escaping is this:
And, I don’t know if this is too general, but you can try this too: