Reputation: 542
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.
Upvotes: 1
Views: 3958
Reputation: 30283
The second version is closer. By putting the result in $newVar
you'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:
regsub -all {[\s\-\]\[$^?+*()|\\%&#]} $varname "_" newVar
Another way to organize that to minimize escaping is this:
regsub -all {[][\s$^?+*()|\\%&#-]} $varname "_" newVar
And, I don't know if this is too general, but you can try this too:
regsub -all {\W} $varname "_" newVar
Upvotes: 3
Reputation: 40763
Another solution is to use the string map
command, which is simpler: the string map command takes in a list of old/new and a string:
set varname [string map {% _ ( _ " " _} $varname]
In the above example, for the sake of brievity, I only replaced %, (, and space " " with an underscore. The disadvantage of this solution is the old/new list can be somewhat long. The advantage is easier to understand.
Upvotes: 2