Home > Enterprise >  I wanted to remove particular pattern from a string in tcl
I wanted to remove particular pattern from a string in tcl

Time:02-10

hreset_error_status_t2_reg1 htrans_flag_t1_reg2 hsize_flag_error_reg check_hwdata_reg

I had to write a Tcl script using regex I have to remove error_status, flag, flag_error, and check in the following strings. It has to search the following keywords in the file and have to remove the mentioned keywords in a string.

CodePudding user response:

To remove all those patterns from a string, use regsub -all. If you don't need to use the power of regular expressions, then string map works well too.

set my_str "hreset_error_status_t2_reg1 htrans_flag_t1_reg2 hsize_flag_error_reg check_hwdata_reg"
set my_regex {error_status_|flag_(error_)?|check_}
regsub -all $my_regex $my_str ""
  --> hreset_t2_reg1 htrans_t1_reg2 hsize_reg hwdata_reg

or

set my_map {
   error_status_  ""
   flag_error_    ""
   flag_          ""
   check_         ""
}
string map $my_map $my_str
   --> hreset_t2_reg1 htrans_t1_reg2 hsize_reg hwdata_reg

Note that I put flag_error_ before flag_ in $my_map so that only the flag_ characters in flag_error weren't removed.

  • Related