Hi i am newbie in TCL please help me with code, method anything. There is a string for example (abcgfhdskls12345)HELLO(hikjkflklfk) (bkjopkjjkl)HI(kjkkjjuilpp)
i just want to remove everything between () and want to print only Hi and Hello
Hi i am newbie in TCL please help me with code, method anything. There is a string for example (abcgfhdskls12345)HELLO(hikjkflklfk) (bkjopkjjkl)HI(kjkkjjuilpp)
i just want to remove everything between () and want to print only Hi and Hello
You could use Tcl regsub
to remove anything with parentheses around it:
set x "(abcgfhdskls12345)HELLO(hikjkflklfk) (bkjopkjjkl)HI(kjkkjjuilpp)"
regsub -all {\(.*?\)} $x {} x
puts $x
which yields:
$ tclsh foo.tcl
HELLO HI
My proposal is to use the regsub
command, which performs substitutions based on regular expressions. You can write something like this:
set str {(abcgfhdskls12345)HELLO(hikjkflklfk) (bkjopkjjkl)HI(kjkkjjuilpp)}
set result [ regsub -all {\(.*?\)} $str {} ]
The -all
option is required because your pattern may appear more than once in the source string and you don't want to strip just the first.
The text inside {...}
is the pattern. You want to match anything that is inside brackets, so you use the \(...\)
part; escaping brackets is required because they have a special meaning in the regular expressions syntax.
Inside brackets you want to match any character repeated zero or more times, so you have .*?
, where the dot means any character and the *?
is the zero-or-more non-greedy repeating command.
You could also split the string on open or close parentheses, and throw out the odd-numbered elements:
set s "(abcgfhdskls12345)HELLO(hikjkflklfk) (bkjopkjjkl)HI(kjkkjjuilpp)"
foreach {out in} [split $s "()"] {puts $out}
HELLO HI
This is also a way using regexp only.
set p {(abcgfhdskls12345)HELLO(hikjkflklfk) (bkjopkjjkl)HI(kjkkjjuilpp)}
set pol [regexp {(.*)(HELLO)(.*) (.*)(HI)(.*)} $p p1 p2 p3 p4 p5 p6]
puts "$p3 $p6"
o/p: HELLO HI