joe
joe

Reputation: 37

TCL pattern matching

I am new to TCL programming. I want to write a tcl code that check if any of the patterns HAT GET DOT present in the given string and if it does, we should display which among the patterns HAT GET DOT is present in the given string. If more than one pattern is present in the string all the matched patterns should be displayed. I wrote the following code, but it only displays a single pattern even if more than one pattern matches the given string.


Can anyone help?

Thank you in advance

Code:

set data1 {asdGETdf ferGETfhgDOT} #data1 is the given string
foreach index $test_data1 {
  set result [regexp  {ABC|ACC|ADC|AXC} $index match]
  puts "\n$index"
  if { $result==1} {
    puts "MATCH:$match"
  } else {
    puts "NO MATCH"
  }  
}

output:-asdGETdf
MATCH:GET

ferGETfhgDOT
MATCH:GET

For the second string I expect it to display GET and DOT (not GET alone as in the output).

I think this is because regexp end the search once a match is found. But how to display all pattern matches?

Upvotes: 0

Views: 1852

Answers (1)

Jerry
Jerry

Reputation: 71598

Simply by using the -all flag. I would also change your script a bit, by using the -inline flag as well to get the results directly instead of relying on match variable because when you get more than one match, it will only keep the last match. I also fixed a few errors from your code snippet.

set data1 {asdGETdf ferGETfhgDOT} ;#data1 is the given string
foreach index $data1 {
  set result [regexp -all -inline -- {HAT|GET|DOT} $index]
  puts "\n$index"
  if {$result != ""} {
      puts "MATCH: $result"
    } else {
      puts "NO MATCH"
  }  
}

regexp manual

Upvotes: 1

Related Questions