2

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

user2901871
  • 219
  • 5
  • 6
  • 10

4 Answers4

3

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
ckhan
  • 4,771
  • 24
  • 26
  • 3
    You should probably use `[^()]*` instead of `.*?` here; that has more predictable behavior when malformatted input is about. (Well, more predictable for non-mavens of RE engines.) – Donal Fellows Oct 21 '13 at 08:33
0

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.

Marco Pallante
  • 3,923
  • 1
  • 21
  • 26
0

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

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
0

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

Yash
  • 23
  • 1
  • 5