stringdictionarytclmqltclsh

How to use left curly bracket and right curly bracket in string map in tcl


I am trying to use string map function in my script. I have a attribute whose value looks like below:

{{1234||}{2345||}}

I want to replace all the opening curly bracket with blank char and ||} with comma ,. How can i use map function?

How to escape the braces in above?


Solution

  • The manual should be clear enough, but just in case...

    set s "{{1234||}{2345||}}"
    set result [string map {"{" "" "||}" ","} $s]
    puts $result
    # 1234,2345,}
    

    string map takes a list containing pair of strings. In each pair in that list going from left to right, the first one will get replaced with the second one.

    Therefore in the above, first { will be replaced with blank, and when this is done, ||} will be replaced with ,. I'm using quotes because braces are used for quoting in Tcl and it might not always work as you want it to if you are not too used to how the quoting mechanism works in Tcl.


    Though I'm not too sure if the above is the result you are looking for? You can use string trimright if you want to remove the extra ,} which will remove all trailing characters that are , and }:

    string trimright $result ",}"
    # 1234,2345
    

    Also sidenote, you escape characters in Tcl using a backslash (\).