tcl string replacement
Asked Answered
H

3

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

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

TEST #### Requested NOT AVAILABLE psy #

Here's what I did, but it is not working.

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

This is where i referenced the function from: http://www.tcl.tk/man/tcl8.5/TclCmd/regsub.htm

Hyperion answered 10/4, 2012 at 18:54 Comment(0)
G
14

The problem is your quoting. You are actually checking for the string "Requested," (including the quotes), but that isn't what you want. Try either getting rid of the squiggly-brackets (}) or 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 that (just replace it with the empty string ""):

regsub -all "," $arg "" arg

or

regsub -all {,} $arg {} arg

As a commenter had mentioned, the latter may be better in the general case, since regular expressions often contain many backslashes (/) and the {} brackets don't require massive amounts of distracting extra backslash escapes the same way that "" quotes do.

Guerin answered 10/4, 2012 at 19:2 Comment(1)
I recommend (almost) always putting regular expressions in braces; they tend to contain many backslashes (especially in any vaguely non-trivial case) and braces make them much easier to write. Putting them in quotes leads to backslashitis…Casement
A
8

Another option, less heavyweight that a regex, is [string map]

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

If you don't want global removal:

set idx [string first , $arg]
set arg [string replace $arg $idx [incr idx]]
Apthorp answered 10/4, 2012 at 22:26 Comment(0)
W
-2
set hfkf "555";
set arg "TEST #### Requested, NOT AVAILABLE psy #;"
regsub -all "Requested," $arg "Requested" arg
regsub -all {"Requested,"} $arg {"Requested"} arg
Wean answered 20/6, 2014 at 11:39 Comment(1)
While your answer may be valid, code only answers should be avoided whenever possible. It is always better to add an explanation about what the code does and how it solves the OP's problem. Thanks !Liris

© 2022 - 2024 — McMap. All rights reserved.