HE 2015-10-08: lsearch returns the first element in list that matches pattern, or -1 if there are no matches.
I want to have the first pattern in list that matches value, or -1 if there are no matches.
Here is my solution:
Syntax: searchPatList mode value patList
where mode is one of:
and value is a string to check if one of the pattern matches.
and patList is a list of pattern. The kind of pattern is defined by mode.
proc searchPatList {mode value patList} { set n 0 switch -exact -- $mode { -exact { foreach el $patList { if {$el eq $value} { return $n } incr n } return -1 } -glob { foreach el $patList { if {[string match $el $value]} { return $n } incr n } } -regexp { foreach el $patList { if {[regexp -- $el $value]} { return $n } incr n } return -1 } default { error "Unknown mode '$mode'!" } } return }
And the examples:
set patList [list \ {test 3.4.1} \ {dummy} \ {^test *[0-9.]*$} \ {test *} \ ] searchPatList -exact {test 3.4.1} $patList 0 searchPatList -exact {test 3.4.2} $patList -1 searchPatList -exact {dummy} $patList 1 searchPatList -glob {test 3.4.1} $patList 0 searchPatList -glob {test 3.4.2} $patList 3 searchPatList -glob {dummy} $patList 1 searchPatList -regexp {test 3.4.1} $patList 0 searchPatList -regexp {test 3.4.2} $patList 2 searchPatList -regexp {dummy} $patList 1 searchPatList -default {dummy} $patList Unknown mode '-default'!