tcl string replacement

半腔热情 提交于 2020-01-01 16:09:42

问题


$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


回答1:


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.




回答2:


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]]



回答3:


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


来源:https://stackoverflow.com/questions/10094697/tcl-string-replacement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!