Tcl string replacement

$arg=TEST #### Requested, NOT AVAILABLE psy #;

      

I have a line above where # is dynamically generated. I have to use a function in tcl to replace a string. Basically I need to remove the comma (,) form of the above expression and display it as

TEST #### Requested NOT AVAILABLE psy #

Here is what I did, but it doesn't work.

regsub -all {"Requested,"} $arg {"Requested"} arg

      

I link to the function here: http://www.tcl.tk/man/tcl8.5/TclCmd/regsub.htm

+3


source to share


3 answers


The problem is quoting. You are actually checking the string "Requested,"

(including quotes), but that is not what you want. Try to either get rid of the sliding brackets ( }

) or the double quotes ( "

):

set arg "TEST #### Requested, NOT AVAILABLE psy #;"
regsub -all "Requested," $arg "Requested" arg

      

If all you need to get rid of is the comma, you can search / replace it (just replace it with an empty string ""

):

regsub -all "," $arg "" arg

      



or

regsub -all {,} $arg {} arg

      

As the commenter already pointed out, the latter might be better in general, since regexes often contain many backslashes ( /

), and parentheses {}

don't require a significant amount of distracting extra backtraces, the way that quotes do ""

.

+11


source


Another lighter weight option, which is a regex, is [string map]

set arg [string map { , "" } $arg]

      



If you don't need a global delete:

set idx [string first , $arg]
set arg [string replace $arg $idx [incr idx]]

      

+8


source


set hfkf "555";
set arg "TEST #### Requested, NOT AVAILABLE psy #;"
regsub -all "Requested," $arg "Requested" arg
regsub -all {"Requested,"} $arg {"Requested"} arg

      

-2


source







All Articles